How to ensure Singleton is not destroyed prematurely? - c++

In my project, I'm working with about 4 singletons made the Scott Meyer's way. One of them:
LevelRenderer& LevelRenderer::Instance()
{
static LevelRenderer obj;
return obj;
}
Now two of those Singletons, LevelRenderer and LevelSymbolTable interact with each other. For example, in this method:
void LevelRenderer::Parse(std::vector<std::string>& lineSet)
{
LevelSymbolTable& table = LevelSymbolTable::Instance();
/** removed code which was irrelevant **/
// for each line in lineSet
BOOST_FOREACH(std::string line, lineSet)
{
// for each character in the line
BOOST_FOREACH(char sym, line)
{
/** code... **/
// otherwise
else
{
sf::Sprite spr;
// Used LevelSymbolTable's Instance here...
table.GenerateSpriteFromSymbol(spr, sym);
// ^ Inside LevelRenderer
/** irrelevant code... **/
}
}
}
}
Now, although the problem hasn't occurred yet. The thing I am afraid of is, what if the LevelSymbolTable instance is already destroyed before I call GenerateSpriteFromSymbol ?
Since I used the Scott Meyer way, the Singleton's instance was allocated by the stack. Hence is is guaranteed to be destroyed using the last created first destroyed rule. Now if LevelSymbolTable's Instance is created after LevelRenderer's Instance, it will be destroyed before LevelRenderer's Instance, right? So then, if I call a method of LevelSymbolTable inside LevelRenderer (especially in LevelRenderer's destructor), I will be treading on undefined behaviour land.
As I said before, this problem hasn't actually occurred while debugging, and is purely my assumption and guess-work. So, is my conclusion correct? Is LevelSymbolTable liable to be destroyed before LevelRenderer. If so, is there any way out of this mess?

You don't have to worry about anything here.* The static keyword guarantees that it is available from when it is initialized to when the program exits. So, you can make a call to a static variable at any point after it has been initialized.
Also, you have a reference to LevelSymbolTable, not a local variable. This is what the ampersand after the class name means. So you can use it locally, but it's really "referring to" the true object which exists somewhere else. So, when the method exits, the reference will go out of scope but the object it refers to will not.
*Well, you may have to worry about one thing. In a destructor, you should just be cleaning up any memory or file references or other things of that nature you have a handle on. I don't know why you would be calling other objects in a destructor.

Define ownership relation between the objects. Either have LevelSymbolTable as member of LevelRenderer:
class LevelRenderer {
LevelSymbolTable symbolTable;
public:
static LevelRenderer& getInstance();
~LevelRenderer() { /* can use symbolTable here */ }
};
Or create one singleton Level that contains both SymbolTable and Renderer:
class Level {
SymbolTable symbolTable;
Renderer levelRenderer; // note the order here
public:
static Level& getInstance();
private:
/* have LeverRenderer save reference to symbol table,
now renderer can use symbol table anywhere */
Level() : levelRenderer(symbolTable)
{ /* ... */ }
};
EDIT: Or get rid of singletons alltogether. See why singletons are bad. I don't know the structure of your application, but from what I see, you could have Level as a normal class that knows how to render itself and has its symbol table. And have its lifetime connected to the level it is supposed to represent in the application.

Static instances will be created at the beginning of the program (before main) and cleaned up at the end (after main), and you can't rely on any particular order in which they are cleaned up. That is, if you have two instances (let's just make them globals for the sake of simplicity)
class one {
one() {}
~one() {}
};
class two {
two() {}
~two() {}
};
one the_one;
two the_other;
int main() {
...
return 0;
}
You cannot and should not make assumptions about the_one being active in the constructor or destructor of the_other. (And vice versa.)
You can, however, rely on them both being active in any other member function, and within main itself.

The scenario you raise in your question is unlikely to occur, because Parse is probably being called while the program is still active. Only when the program is about to exit would destructors be called.
In you comments, you indicate a slightly different worry, which is global destructor interdependency. This might actually occur if you have global objects that register themselves with some global container. You might expect that objects would remove themselves from the container, and that the container would eject objects.
One way to deal with this is to allow the container to take ownership of the objects that register with it. This means that what gets registered with the global container are dynamically allocated instances, rather than your Scott Meyer's singleton instances. Then, the global container would take charge of cleaning up the registered items when its global destructor is called.

Related

Memory managed C++ singletons

I'm programming a game engine right now. The hardest part for me has been the memory management. I've been putting in as many optimizations as possible (because every frame counts, right?) and realized that the best way to approach this would be to do resource management using Stack and Pool allocators. The problem is, I can't figure out how to make a singleton class that is memory managed by these allocators.
My singletons are managers, so they are actually rather big, and memory management of them is important for the start up speed of my game. I basically want to be able to call my allocators' alloc() functions, which return type void*, and create my singleton in this allocated space.
I've been thinking about putting a static boolean called instantiated in each singleton class and having the constructor return NULL if instantiated is true. Would this work?
This is why everybody thinks Singletons suck. They suck horrifically. This is but one aspect of their suck, which will suck down your whole application with it.
In order to solve your problem: Do not use Suckletons.
Ok so I will answer this by sharing my own experience. Normally I want a class to have all its own functionality and later realize ok this might need a factory method to supply other code with an instance of my object that is singular. The instance really should only be defined once to maintain state etc. Therefore this is what I do for classes that don't have all of their initialization wrapped into construction. I don't want to clutter my existing class with singletonsuxness so I create a factory wrapper class to help me with this. You could use Myer's singleton pattern which is elegant and encapsulates the locking by letting the implementation of the static local variable (relies on compiler implementation of static local init which is not always a good idea) handle the locking but the problem comes if you, like me, want your objects default constructed so that you can use STL vectors etc on them easily and later call some type of initialization on them, possibly passing parameters to this method, to make them heavier.
class X
{
public:
bool isInitialized () { return _isInitialized; } ; // or some method like
// establishCxn to have it
// bootstrapped
void initialize();
X() {} // constructor default, not initialized, light weight object
private:
bool _isInitialzied;
};
// set initialization to false
X::X(): _isInitialized(false) {}
void X::intialize()
{
if (isInitiazlied()) { return; }
.... init code ....
_isInitialized = true
}
// now we go ahead and put a factory wrapper on top of this to help manage the
// singletoness nature. This could be templatized but we don't as we want the
// flexibility to override our own getinstance to call a specific initialize for the
// object it is holding
class XFactory
{
public:
static X* getInstance();
private:
static boost::mutex _lock;
// light weight static object of yourself ( early instantiation ) to put on the stack
// to avoid thread issues, static method member thread saftey, and DCLP pattern
// threading races that can stem from compiling re-ordering of items
static XFactory _instance;
// making this pointer volatile so that the compiler knows not to reorder our
// instructions for it ( depends on compiler implementation but it is a safe guard )
X* volatile _Xitem;
X* getXitem () { return _Xitem; }
void createInstance();
void doCleanUp();
// stop instantiation or unwanted copies
XClientFactory();
~XClientFactory();
XClientFactory(XClientFactory const&);
XClientFactory& operator=(XClientFactory const&);
};
// on construction we create and set the pointer to a new light weight version of the
// object we are interested in construction
XFactory::XFactory() : _Xitem( new X; )
{
}
// note our factory method is returning a pointer to X not itself (XFactory)
X* XFactory::getInstance()
{
// DCLP pattern, first thread might have initialized X while others
// were waiting for the lock in this way your double check locking is
// on initializing the X container in the factory and not the factory object itself.
// Worst case your initialization could happen more than once but it should check the
// boolean before it starts (see initialization method above) and sets the boolean at
// the end of it. Also your init should be such that a re-initialization will not put
// the object in a bad state. The most important thing to note is that we
// moved the double check locking to the contained object's initialization method
// instead of the factory object
if (! XFactory::_instance.getXitem()->isInitialized() )
{
boost::unique_lock<boost::mutex> guard(XFactory::_lock);
if (! XFactory::_instance.getXitem()->isInitialized() )
{
XFactory::_instance.getXitem()->initialize();
}
}
return XFactory::_instance.getXitem();
}
// XFactory private static instance on the stack will get cleaned up and we need to
// call the delete on the pointer we created for the _Xitem
XFactory::~XFactory()
{
doCleanUp();
}
XFactory::doCleanUp()
{
delete _Xitem; //
}
That's it, let me know what you think. I also wrestled recently with singleton and all the pit falls. Also, we are not using a 0x compiler yet that would ensure that the Myers singleton will be implemented in a thread safe way just using a local static variable

Managing a singleton destructor

The following small example implements a singleton pattern that I've seen many times:
#include <iostream>
class SingletonTest {
private:
SingletonTest() {}
static SingletonTest *instance;
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest *get_instance() {
if(!instance) instance = new SingletonTest;
return instance;
}
};
SingletonTest *SingletonTest::instance = 0;
int main(int argc, char *argv[]) {
SingletonTest *s = SingletonTest::get_instance();
return 0;
}
The main problem I have with this is that the destructor of my singleton is never called.
I can instead make instance a (c++0x?) shared_ptr, which works well - except that it means my destructor has to be public.
I could add a static 'cleanup' method but that opens up the possibility of user error (i.e. forgetting to call it). It would also not allow for proper cleanup in the face of (unhandled) exceptions.
Is there a common strategy/pattern that will allow lazy instantiation, 'automatically' call my destructor, and still allow me to keep the destructor private?
...not exactly a direct answer, but too long for a comment - why not do the singleton this way:
class SingletonTest {
private:
SingletonTest() {}
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest& get_instance() {
static SingletonTest instance;
return instance;
}
};
Now you have a lazy singleton that will be destructed on exit... It's not any less re-entrant than your code...
You could write a deinitialization function and call atexit() inside the object constructor to register it. Then when C++ runtime deinitializes the module it will at some point after main() call your deinitialization function. That bold italic is there because you get rather loose control on when exactly it is called and that can lead to deinitialization order fiasco - be careful.
You could always friend the shared_ptr (or rather scoped_ptr, which is more fitting) to allow it access to your private destructor.
Note that there's also the system atexit() function which can register a function to call at the end of the application. You could pass a static function of your singleton that just does delete instanance; to it.
Note that it's usually a good idea separates the class that is to be a singleton from the singleton-ness of it. Especially for testing and/or when you do need the doubleton. :)
While I'm at it, try to avoid lazy initialization. Initialize/create your singletons at startup, in a well determined order. This allows them to shut down properly and resolves dependencies without surprises. (I have had cyclic singleton hell... it's easier than you think...)
You can use a private destructor with shared_ptr by passing in a deleter that has access to the destructor (such as a class defined as a member of SingletonTest).
However, you need to be very careful when destroying singletons to ensure that they are not used after they are destroyed. Why not just use a plain global variable anyway?
if you declare the class which does the actual delete op as a friend (let it be shared_ptr<SingletonTest> or some kind of default deleter) a friend, your destructor can be private.
Although i dont see any necessarity for making it private.
The first question is: do you want the singleton to be destructed.
Destructing a singleton can lead to order of destruction problems; and
since you're shutting down, the destructor can't be necessary to
maintain program invariants. About the only time you want to run the
destructor of a singleton is if it manages resources that the system
won't automatically clean up, like temporary files. Otherwise, it's
better policy to not call the destructor on it.
Given that, if you want the destructor to be called, there are two
alternatives: declare the single object as a static local variable in
the instance function, or use std::auto_ptr or something similar,
instead of a raw pointer, as the pointer to it.

how can I check if an object exists in C++

I am trying to write a function that will check if an object exists:
bool UnloadingBay::isEmpty() {
bool isEmpty = true;
if(this->unloadingShip != NULL) {
isEmpty = false;
}
return isEmpty;
}
I am pretty new to C++ and not sure if my Java background is confusing something, but the compiler gives an error:
UnloadingBay.cpp:36: error: no match for ‘operator!=’ in ‘((UnloadingBay*)this)->UnloadingBay::unloadingShip != 0’
I can't seem to figure out why it doesn't work.
Here is the declaration for class UnloadingBay:
class UnloadingBay {
private:
Ship unloadingShip;
public:
UnloadingBay();
~UnloadingBay();
void unloadContainer(Container container);
void loadContainer(Container container);
void dockShip(Ship ship);
void undockShip(Ship ship);
bool isEmpty();
};
It sounds like you may need a primer on the concept of a "variable" in C++.
In C++ every variable's lifetime is tied to it's encompassing scope. The simplest example of this is a function's local variables:
void foo() // foo scope begins
{
UnloadingShip anUnloadingShip; // constructed with default constructor
// do stuff without fear!
anUnloadingShip.Unload();
} // // foo scope ends, anything associated with it guaranteed to go away
In the above code "anUnloadingShip" is default constructed when the function foo is entered (ie its scope is entered). No "new" required. When the encompassing scope goes away (in this case when foo exits), your user-defined destructor is automatically called to clean up the UnloadingShip. The associated memory is automatically cleaned up.
When the encompassing scope is a C++ class (that is to say a member variable):
class UnloadingBay
{
int foo;
UnloadingShip unloadingShip;
};
the lifetime is tied to the instances of the class, so when our function creates an "UnloadingBay"
void bar2()
{
UnloadingBay aBay; /*no new required, default constructor called,
which calls UnloadingShip's constructor for
it's member unloadingShip*/
// do stuff!
} /*destructor fires, which in turn trigger's member's destructors*/
the members of aBay are constructed and live as long as "aBay" lives.
This is all figured out at compile time. There is no run-time reference counting preventing destruction. No considerations are made for anything else that might refer to or point to that variable. The compiler analyzes the functions we wrote to determine the scope, and therefore lifetime, of the variables. The compiler sees where a variable's scope ends and anything needed to clean up that variable will get inserted at compile time.
"new", "NULL", (don't forget "delete") in C++ come into play with pointers. Pointers are a type of variable that holds a memory address of some object. Programmers use the value "NULL" to indicate that a pointer doesn't hold an address (ie it doesn't point to anything). If you aren't using pointers, you don't need to think about NULL.
Until you've mastered how variables in C++ go in and out of scope, avoid pointers. It's another topic entirely.
Good luck!
I'm assuming unloadingShip is an object and not a pointer so the value could never be NULL.
ie.
SomeClass unloadingShip
versus
SomeClass *unloadingShip
Well, you don't have to write so much code to check if a pointer is NULL or not. The method could be a lot simpler:
bool UnloadingBay::isEmpty() const {
return unloadingShip == NULL;
}
Plus, it should be marked as "const" because it does not modify the state of the object and can be called on constant instances as well.
In your case, "unloadingShip" is an object of class "UnloadingShip" which is not dynamically allocated (except when the whole class "UnloadingBay" is allocated dynamically). Thus, checking if it equals to NULL doesn't make sense because it is not a pointer.
For checking, if an object exists, you can consider going this way:
create a pointer to your object:
someClass *myObj = NULL // Make it null
and now where you pass this pointer, you can check:
if(!myObj) // if its set null, it wont pass this condition
myObj = new someClass();
and then in case you want to delete, you can do this:
if(myobj)
{
delete myObj;
myObj = NULL;
}
so in this way, you can have a good control on checking whether your object exists, before deleting it or before creating a new one.
Hope this helps!

How to handle 'this' pointer in constructor?

I have objects which create other child objects within their constructors, passing 'this' so the child can save a pointer back to its parent. I use boost::shared_ptr extensively in my programming as a safer alternative to std::auto_ptr or raw pointers. So the child would have code such as shared_ptr<Parent>, and boost provides the shared_from_this() method which the parent can give to the child.
My problem is that shared_from_this() cannot be used in a constructor, which isn't really a crime because 'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations.
Google's C++ Style Guide states that constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. This solves the 'this-in-constructor' problem as well as a few others as well.
What bothers me is that people using your code now must remember to call Init() every time they construct one of your objects. The only way I can think of to enforce this is by having an assertion that Init() has already been called at the top of every member function, but this is tedious to write and cumbersome to execute.
Are there any idioms out there that solve this problem at any step along the way?
Use a factory method to 2-phase construct & initialize your class, and then make the ctor & Init() function private. Then there's no way to create your object incorrectly. Just remember to keep the destructor public and to use a smart pointer:
#include <memory>
class BigObject
{
public:
static std::tr1::shared_ptr<BigObject> Create(int someParam)
{
std::tr1::shared_ptr<BigObject> ret(new BigObject(someParam));
ret->Init();
return ret;
}
private:
bool Init()
{
// do something to init
return true;
}
BigObject(int para)
{
}
BigObject() {}
};
int main()
{
std::tr1::shared_ptr<BigObject> obj = BigObject::Create(42);
return 0;
}
EDIT:
If you want to object to live on the stack, you can use a variant of the above pattern. As written this will create a temporary and use the copy ctor:
#include <memory>
class StackObject
{
public:
StackObject(const StackObject& rhs)
: n_(rhs.n_)
{
}
static StackObject Create(int val)
{
StackObject ret(val);
ret.Init();
return ret;
}
private:
int n_;
StackObject(int n = 0) : n_(n) {};
bool Init() { return true; }
};
int main()
{
StackObject sObj = StackObject::Create(42);
return 0;
}
Google's C++ programming guidelines have been criticized here and elsewhere again and again. And rightly so.
I use two-phase initialization only ever if it's hidden behind a wrapping class. If manually calling initialization functions would work, we'd still be programming in C and C++ with its constructors would never have been invented.
Depending on the situation, this may be a case where shared pointers don't add anything. They should be used anytime lifetime management is an issue. If the child objects lifetime is guaranteed to be shorter than that of the parent, I don't see a problem with using raw pointers. For instance, if the parent creates and deletes the child objects (and no one else does), there is no question over who should delete the child objects.
KeithB has a really good point that I would like to extend (in a sense that is not related to the question, but that will not fit in a comment):
In the specific case of the relation of an object with its subobjects the lifetimes are guaranteed: the parent object will always outlive the child object. In this case the child (member) object does not share the ownership of the parent (containing) object, and a shared_ptr should not be used. It should not be used for semantic reasons (no shared ownership at all) nor for practical reasons: you can introduce all sorts of problems: memory leaks and incorrect deletions.
To ease discussion I will use P to refer to the parent object and C to refer to the child or contained object.
If P lifetime is externally handled with a shared_ptr, then adding another shared_ptr in C to refer to P will have the effect of creating a cycle. Once you have a cycle in memory managed by reference counting you most probably have a memory leak: when the last external shared_ptr that refers to P goes out of scope, the pointer in C is still alive, so the reference count for P does not reach 0 and the object is not released, even if it is no longer accessible.
If P is handled by a different pointer then when the pointer gets deleted it will call the P destructor, that will cascade into calling the C destructor. The reference count for P in the shared_ptr that C has will reach 0 and it will trigger a double deletion.
If P has automatic storage duration, when it's destructor gets called (the object goes out of scope or the containing object destructor is called) then the shared_ptr will trigger the deletion of a block of memory that was not new-ed.
The common solution is breaking cycles with weak_ptrs, so that the child object would not keep a shared_ptr to the parent, but rather a weak_ptr. At this stage the problem is the same: to create a weak_ptr the object must already be managed by a shared_ptr, which during construction cannot happen.
Consider using either a raw pointer (handling ownership of a resource through a pointer is unsafe, but here ownership is handled externally so that is not an issue) or even a reference (which also is telling other programmers that you trust the referred object P to outlive the referring object C)
A object that requires complex construction sounds like a job for a factory.
Define an interface or an abstract class, one that cannot be constructed, plus a free-function that, possibly with parameters, returns a pointer to the interface, but behinds the scenes takes care of the complexity.
You have to think of design in terms of what the end user of your class has to do.
Do you really need to use the shared_ptr in this case? Can the child just have a pointer? After all, it's the child object, so it's owned by the parent, so couldn't it just have a normal pointer to it's parent?

Destruction order of static objects in C++

Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?
The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.
The other answers to this insist that it can't be done. And they're right, according to the spec -- but there is a trick that will let you do it.
Create only a single static variable, of a class or struct that contains all the other things you would normally make static variables, like so:
class StaticVariables {
public:
StaticVariables(): pvar1(new Var1Type), pvar2(new Var2Type) { };
~StaticVariables();
Var1Type *pvar1;
Var2Type *pvar2;
};
static StaticVariables svars;
You can create the variables in whatever order you need to, and more importantly, destroy them in whatever order you need to, in the constructor and destructor for StaticVariables. To make this completely transparent, you can create static references to the variables too, like so:
static Var1Type &var1(*svars.var1);
Voilà -- total control. :-) That said, this is extra work, and generally unnecessary. But when it is necessary, it's very useful to know about it.
Static objects are destroyed in the reverse of the order in which they're constructed (e.g. the first-constructed object is destroyed last), and you can control the sequence in which static objects are constructed, by using the technique described in Item 47, "Ensure that global objects are initialized before they're used" in Meyers' book Effective C++.
For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static onject?
Ensure that it's constructed before the other static object.
How can I control the construction order? not all of the statics are in the same dll.
I'll ignore (for simplicity) the fact that they're not in the same DLL.
My paraphrase of Meyers' item 47 (which is 4 pages long) is as follows. Assuming that you global is defined in a header file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
... add some code to that include file like this ...
//GlobalA.h
extern GlobalA globalA; //declare a global
class InitA
{
static int refCount;
public:
InitA();
~InitA();
};
static InitA initA;
The effect of this will be that any file which includes GlobalA.h (for example, your GlobalB.cpp source file which defines your second global variable) will define a static instance of the InitA class, which will be constructed before anything else in that source file (e.g. before your second global variable).
This InitA class has a static reference counter. When the first InitA instance is constructed, which is now guaranteed to be before your GlobalB instance is constructed, the InitA constructor can do whatever it has to do to ensure that the globalA instance is initialized.
Short answer: In general, no.
Slightly longer answer: For global static objects in a single translation-unit the initialization order is top to bottom, the destruction order is exactly reverse. The order between several translation-units is undefined.
If you really need a specific order, you need to make this up yourself.
Theres no way to do it in standard C++ but if you have a good working knowledge of your specific compiler internals it can probably be achieved.
In Visual C++ the pointers to the static init functions are located in the .CRT$XI segment (for C type static init) or .CRT$XC segment (for C++ type static init) The linker collects all declarations and merges them alphabetically. You can control the order in which static initialization occurs by declaring your objects in the proper segment using
#pragma init_seg
for example, if you want file A's objects to be created before file B's:
File A.cpp:
#pragma init_seg(".CRT$XCB")
class A{}A;
File B.cpp:
#pragma init_seg(".CRT$XCC")
class B{}B;
.CRT$XCB gets merged in before .CRT$XCC. When the CRT iterates through the static init function pointers it will encounter file A before file B.
In Watcom the segment is XI and variations on #pragma initialize can control construction:
#pragma initialize before library
#pragma initialize after library
#pragma initialize before user
...see documentation for more
Read:
SO Initialization Order
SO Solving the Order of Initialization Problem
No, you can't. You should never rely on the other of construction/destruction of static objects.
You can always use a singleton to control the order of construction/destruction of your global resources.
Do you really need the variable to be initialized before main?
If you don't you can use a simple idiom to actually control the order of construction and destruction with ease, see here:
#include <cassert>
class single {
static single* instance;
public:
static single& get_instance() {
assert(instance != 0);
return *instance;
}
single()
// : normal constructor here
{
assert(instance == 0);
instance = this;
}
~single() {
// normal destructor here
instance = 0;
}
};
single* single::instance = 0;
int real_main(int argc, char** argv) {
//real program here...
//everywhere you need
single::get_instance();
return 0;
}
int main(int argc, char** argv) {
single a;
// other classes made with the same pattern
// since they are auto variables the order of construction
// and destruction is well defined.
return real_main(argc, argv);
}
It does not STOP you to actually try to create a second instance of the class, but if you do the assertion will fail. In my experience it works fine.
You can effectively achieve similar functionality by having a static std::optional<T> instead of a T. Just initialize it as you'd do with a variable, use with indirection and destroy it by assigning std::nullopt (or, for boost, boost::none).
It's different from having a pointer in that it has preallocated memory, which is I guess what you want. Therefore, if you destroy it & (perhaps much later) recreate it, your object will have the same address (which you can keep) and you don't pay the cost of dynamic allocation/deallocation at that time.
Use boost::optional<T> if you don't have std:: / std::experimental::.