A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
singleton.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2007 INRIA
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
7 */
8#ifndef SINGLETON_H
9#define SINGLETON_H
10
11/**
12 * \file
13 * \ingroup singleton
14 * ns3::Singleton declaration and template implementation.
15 */
16
17namespace ns3
18{
19
20/**
21 * \ingroup core
22 * \defgroup singleton Singleton
23 *
24 * Template class implementing the Singleton design pattern.
25 */
26
27/**
28 * \ingroup singleton
29 * \brief A template singleton
30 *
31 * This template class can be used to implement the singleton pattern.
32 * The underlying object will be destroyed automatically when the process
33 * exits.
34 *
35 * For a singleton whose lifetime is bounded by the simulation run,
36 * not the process, see SimulationSingleton.
37 *
38 * To force your `class ExampleS` to be a singleton, inherit from Singleton:
39 * \code
40 * class ExampleS : public Singleton<ExampleS> { ... };
41 * \endcode
42 *
43 * Then, to reach the singleton instance, just do
44 * \code
45 * ExampleS::Get ()->...;
46 * \endcode
47 *
48 * \note
49 * If you call Get() again after the object has
50 * been destroyed, the object will be re-created which will result in a
51 * memory leak as reported by most memory leak checkers. It is up to the
52 * user to ensure that Get() is never called from a static variable
53 * finalizer.
54 */
55template <typename T>
57{
58 public:
59 // Delete copy constructor and assignment operator to avoid misuse
60 Singleton(const Singleton<T>&) = delete;
61 Singleton& operator=(const Singleton<T>&) = delete;
62
63 /**
64 * Get a pointer to the singleton instance.
65 *
66 * The instance will be automatically deleted when
67 * the process exits.
68 *
69 * \return A pointer to the singleton instance.
70 */
71 static T* Get();
72
73 protected:
74 /** Constructor. */
76 {
77 }
78
79 /** Destructor. */
80 virtual ~Singleton()
81 {
82 }
83};
84
85} // namespace ns3
86
87/********************************************************************
88 * Implementation of the templates declared above.
89 ********************************************************************/
90
91namespace ns3
92{
93
94template <typename T>
95T*
97{
98 static T object;
99 return &object;
100}
101
102} // namespace ns3
103
104#endif /* SINGLETON_H */
A template singleton.
Definition singleton.h:57
Singleton(const Singleton< T > &)=delete
Singleton & operator=(const Singleton< T > &)=delete
static T * Get()
Get a pointer to the singleton instance.
Definition singleton.h:96
Singleton()
Constructor.
Definition singleton.h:75
virtual ~Singleton()
Destructor.
Definition singleton.h:80
Every class exported by the ns3 library is enclosed in the ns3 namespace.