Is it right way to create sinlgeton class by weak_ptr - c++

I create a parent class to handle singleton pattern with smart pointer:
.h file:
template<class singleType>
class Singleton
{
public:
static std::shared_ptr<singleType> GetInstance();
private:
static std::weak_ptr<singleType> m_singleObject;
};
.cpp file:
template<class singleType>
std::shared_ptr<singleType> Singleton<singleType>::GetInstance()
{
auto shareObject = m_singleObject.Lock();
if (!shareObject)
{
shareObject.reset(new singleType);
m_singleObject = shareObject;
}
return shareObject;
}
Not sure it is the right way to use smart pointer?
Any idea?
Many Thanks

The pros and cons of this implementation are already discussed. But there are a bunch of bugs:
1) As this is a template you have to move your implementation into the header or the linker cannot find it.
2) The .lock() function of the weak_ptr is not in capitals.
3) Don't forget to instantiate
template<class singleType>
std::weak_ptr<singleType> Singleton<singleType>::m_singleObject;
4) Better use shareObject = std::make_shared<singleType>(singleType()); instead of the new: http://herbsutter.com/gotw/_103/
5) As Konrad mentioned: it's not thread-safe.

I did some research so now I'll post an answer.
The code all looks like it should work and is a correct usage of smart pointers. The only question is how exactly you want the singleton to behave. This should behave like a textbook singleton EXCEPT for the behavior that if nothing currently has a pointer to the singleton, it will delete itself. This behavior is something that really depends on the implementation of your program. If you want the singelton to only exist when it is in use, then I'd say go for it.
I would just avoid creating and destroying the singelton too often especially if the construction and deconstruction are particularly intensive. If it is constantly getting created and deleted then you are probably better off with a more standard singleton implementation. The standard singleton behavior tends to be that a singleton is only created once during the duration of the program running and is never deleted.
I think this is a clever implementation given you have a use for it and I might have to borrow the idea.

Your code isn’t thread safe.
The name lock may suggest that concurrent access is blocked but in fact there’s no such guarantee: when multiple threads concurrently call your GetInstance function you will get several instances instead of guaranteeing a single one.
You need to create an explicit lock for the whole duration of the GetInstance function’s lifetime. Note that this is of course not very efficient.

To the best of my knowledge this should be fine. You'll avoid out of order destruction issues, but it could be a problem to create new instances after your initial instance is created. This singleton will have only one instance alive at any time, but over the course of the program running more than one instance may have been alive overall.
This destruction and recreation may also be unwanted in terms of performance, not only in side-effects.

Related

Suicide object implementation leveraging `std::weak_ptr`

I'm considering using "suicide objects" to model entities in a game, that is, objects able to delete themselves. Now, the usual C++03 implementation (plain old delete this) does nothing for other objects potentially refering to the suicide object, which is why I'm using std::shared_ptr and std::weak_ptr.
Now for the code dump :
#include <memory>
#include <iostream>
#include <cassert>
struct SuObj {
SuObj() { std::cout << __func__ << '\n'; }
~SuObj() { std::cout << __func__ << '\n'; }
void die() {
ptr.reset();
}
static std::weak_ptr<SuObj> create() {
std::shared_ptr<SuObj> obj = std::make_shared<SuObj>();
return (obj->ptr = std::move(obj));
}
private:
std::shared_ptr<SuObj> ptr;
};
int main() {
std::weak_ptr<SuObj> obj = SuObj::create();
assert(!obj.expired());
std::cout << "Still alive\n";
obj.lock()->die();
assert(obj.expired());
std::cout << "Deleted\n";
return 0;
}
Question
This code appears to work fine. However, I'd like to have someone else's eye to gauge it. Does this code make sense ? Did I blindly sail into undefined lands ? Should I drop my keyboard and begin art studies right now ?
I hope this question is sufficiently narrowed down for SO. Seemed a bit tiny and low-level for CR.
Minor precision
I do not intend to use this in multithreaded code. If the need ever arises, I'll be sure to reconsider the whole thing.
When you have shared_ptr based object lifetime, the lifetime of your object is the "lifetime" of the union of the shared_ptrs who own it collectively.
In your case, you have an internal shared_ptr, and your object will not die until that internal shared_ptr expires.
However, this does not mean you can commit suicide. If you remove that last reference, your object continues to exist if anyone has .lock()'d the weak_ptr and stored the result. As this is the only way you can access the object externally, it may happen1.
In short, die() can fail to kill the object. It might better be called remove_life_support(), as something else could keep the object alive after said life support is removed.
Other than that, your design works.
1
You could say "well, then callers should just not keep the shared_ptr around" -- but that doesn't work, as the check that the object is valid is only valid as long as the shared_ptr persists. Plus, by exposing the way to create shared_ptr, you have no type guarantees that the client code won't store them (accidentally or on purpose).
A transaction based model (where you pass a lambda in, and it operates on it internally) could help with this if you want seriously paranoid robustness.
Or you can live with the object sometimes living too long.
Consider hiding these messy details behind a Regular Type (or almost-regular) that has a pImpl to the nasty memory management problem. That pImpl could be a weak_ptr with the above semantics.
Then users of your code need only interact with the Regular (or pseudoRegular) wrapper.
If you don't want cloning to be easy, disable copy construction/assignment and only expose move.
Now your nasty memory management is hiding behind a fascade, and if you decide you did it all wrong the external pseudoRegular interface can have different guts.
Regular type in C++11
Not a direct answer but potentially useful information.
In Chromium codebase there is a concept of exactly what you are trying to achieve. They call it WeakPtrFactory. Their solution cannot be directly taken into your code since they have their own implementation of e.g. shared_ptr and weak_ptr but design wise it can be of use to you.
I made a try to implement it and found out that the problem of double deletion can be solved by passing into inner shared_ptr custom empty deleter - from this moment on neither shared_ptrs created from weak_ptr not inner shared_ptr will be able to call destructor (again) on your object.
The only problem to solve is what if your object is deleted and somewhere else you keep shared_ptr to it? But from what I see it cannot be simply solved by any magic mean and require designing that whole project the way that it simply never happens e.g. by using shared_ptr only in local scope and ensuring that some set of operations (creating suicide object, using it, ordering its suicide) could be performed only in the same thread.
I understand you're trying to create a minimal example for SO, but I see a few challenges you'll want to consider:
You have a public constructor and destructor, so technically there's no guarantee that the create() method is always used.
You could make those protected or private but that decision would interfere with use with std algorithms and containers.
This doesn't guarantee that the object will actually destruct because as long as someone has a shared_ptr it's going to exist. That may or may not be a problem for your use case, but because of that I don't think this will add as much value as you're heading.
This is likely going to be confusing and counter-intuitive to other developers. It might make maintenance harder, even if your intent is to make it easier. That's a bit of a value judgement, but I'd encourage you to consider if it's truly easier to manage.
I commend you for putting thought into memory management up front. Disciplined use of shared_ptr and weak_ptr will help with your memory management issues -- I'd counsel against trying to have the instance try to manage its own lifecycle.
As for art studies... I'd only recommend that if that's truly your passion! Good luck!

Is there a way to force an object to be created on the heap with shared_ptr?

i was wondering if it is possible to force an object to be created on the heap by creating a private/protected desctuctor and by using shared_ptrs to ensure an automatic resource managment (the RAII features of a shared_ptr) at the same time.
Can that be done in a different way maybe?
The reason i ask that, is because from what i heard(didnt look at that yet) at the STL there are no virtual descructors,so there is no way to ensure safe destruction other than...shared_ptr?
And if so,there is no way to force the object to the heap since shared_ptr is trying to access the destuctor.
Anyway to bypass these limitations?
C++ is a language that puts the correctness of the code in the hand of the programmer. Trying to alter that via some convoluted methods typically leads to code that is hard to use or that doesn't work very well. Forcing the hand of the programmer so that (s)he has to create an object on the heap even if that's not "right" for that particular situation is just bad. Let the programmer shoot him-/herself in the foot if he wants to.
In larger projects, code should be reviewed by peers (preferably at least sometimes by more senior staff) for correctness and that it follows the coding guidelines of the project.
I'm not entirely sure how "virtual destructors" relate to "safe destruction" and "shared pointers" - these are three different concepts that are not very closely related - virtual destructors are needed when a class is used as a base-class to derive a new class. STL objects are not meant to be derived from [as a rule, you use templates OR inheritance, although they CAN be combined, it gets very complicated very quickly when you do], so there is no need to use virtual destructors in STL.
If you have a class that is a baseclass, and the storage is done based on pointers or references to the baseclass, then you MUST have virtual destructors - or don't use inheritance.
"safe destruction", I take it, means "no memory leaks" [rather than "correct destruction", which can of course also be a problem - and cause problems with memory leaks]. For a large number of situations, this means "don't use pointers to the object in the first place". I see a lot of examples here on SO where the programmer is calling new for absolutely no reason. vector<X>* v = new vector<X>; is definitely a "bad smell" (Just like fish or meat, something is wrong with the code if it smells bad). And if you are calling new, then using shared pointer, unique pointer or some other "wrapping" is a good idea. But you shouldn't force that concept - there are occasionally good reasons NOT to do that.
"shared pointer" is a concept to "automatically destroy the object when it is no longer in use", which is a useful technique to avoid memory leaks.
Now that I have told you NOT to do this, here's one way to achieve it:
class X
{
private:
int x;
X() : x(42) {};
public:
static shared_ptr<X> makeX() { return make_shared<X>(); }
};
Since the constructor is private, the "user" of the class can't call "new" or create an object of this kind. [You probably also want to put the copy constructor and assignment operator in private or use delete to prevent them from being used].
However, I still think this is a bad idea in the first place.
The answer by Mats is indeed wrong. The make_shared needs a public constructor.
However, the following is valid:
class X
{
private:
int x;
X() : x( 42 ) {};
public:
static std::shared_ptr<X> makeX()
{
return std::shared_ptr<X>( new X() );
}
};
I don't like to use the new keyword, but in this case, it is the only way.

Difference between Singleton implemention using pointer and using static object

EDIT: Sorry my question was not clear, why do books/articles prefer implementation#1 over implementation#2?
What is the actual advantage of using pointer in implementation of Singleton class vs using a static object? Why do most books prefer this
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
over this
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
protected:
Singleton(); // Prevent construction
Singleton(const Singleton&); // Prevent construction by copying
Singleton& operator=(const Singleton&); // Prevent assignment
~Singleton(); // Prevent unwanted destruction
};
why do books/articles prefer implementation#1 over implementation#2?
Because most articles describing the Singleton anti-pattern don't fully understand all the hidden dangers when trying to implement it safely in C++. It's surprisingly difficult to get it right.
What is the actual advantage of using pointer in implementation of Singleton class vs using a static object?
Using a pointer, with new but no delete, ensures that the object will never be destroyed, so there is no danger of accessing it after its lifetime has ended. Combined with the "lazy" creation, the first time that it's accessed, this guarantees that all accesses are to a valid object. The disadvantages are that creation is not thread-safe, and that the object and any resources it acquires are not released at the end of the program.
Using a local static object, creation is thread-safe on any compiler that supports the C++11 threading model; also, the object will be destroyed at the end of the program. However, it is possible to access the object after its destruction (e.g. from the destructor of another static object), which could lead to nasty bugs.
The best option is to avoid static data, and globally-accessible data, as much as possible. In particular, never use the Singleton anti-pattern; it combines global, static data with weird instantiation restrictions that make testing unnecessarily difficult.
The second version (using a local static variable) has significant advantages.
It does not require use of the free-store, and so will not be detected as a memory leak. It is thread-safe (in C++11). It is shorter and simpler.
The only downsides are that it is impossible to make it portably threadsafe (for pre-C++11 compilers), and that it does not give you the option of explicitly destroying the singleton instance.
I'd always prefer the second, but the first does have a couple of potentially interesting advantages:-
Clarity - the checking of the pointer being null is effectively
what the compiler does under the hood when constructing static
objects. From a 'learning' perspective, it's instructive to
understand what's happening when you use static objects in method
scope.
Lazy Allocation - in the first case, the Singleton object is
heap-allocated. If your function never runs, the object is never
constructed and never consumes memory. But, in the second case,
memory is assigned by the linker to hold the object before the
program starts, even though 'construction' is lazy.
The second example is known by the name "Meyers' Singleton", because it was published first in either "Effective C++", or "More Effective C++". I'm not sure which one, but both were published after "Design Patterns" - so the Gang of Four might just as well have been unaware of the second pattern when their book was written.
Also, the first approach is much more standard for other languages - you can do the first one in Java or C#, but not the second, so people coming from different backgrounds could be another reason for the first one to be more famous.
On the technical side, with the first approach you can control when the singleton is destroyed, but this could also bring you a lot of headaches.
The second one has non-deterministic destruction. The first one, you are in control as to when you delete the pointer, if at all.
The first construct is not thread-safe, of course, but can be made so with boost::call_once (or std::call_once if available)
The second construct was common enough that many compilers made it thread-safe even if technically by the standard it isn't (although by the standard the object should only be created once, I'm not sure about the standard's view on completion of the construction before another thread uses it).
If there is no issue with the order of destruction then you can go ahead and use the static version, as long as your compiler guarantees it as thread-safe.
One advantage is that you do not have to check whether the singleton has already been instantiated.
Another is that you do not have to worry about de-allocating any memory.
How about a non-local static? Anyone see a problem with this?
class Singleton
{
static Singleton singleton;
Singleton();
// etc
public:
static Singleton &Instance() { return singleton; }
};
Singleton Singleton::singleton;
// etc

delete this & private destructor

I've been thinking about the possible use of delete this in c++, and I've seen one use.
Because you can say delete this only when an object is on heap, I can make the destructor private and stop objects from being created on stack altogether. In the end I can just delete the object on heap by saying delete this in a random public member function that acts as a destructor. My questions:
1) Why would I want to force the object to be made on the heap instead of on the stack?
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Any scheme that uses delete this is somewhat dangerous, since whoever called the function that does that is left with a dangling pointer. (Of course, that's also the case when you delete an object normally, but in that case, it's clear that the object has been deleted). Nevertheless, there are somewhat legitimate cases for wanting an object to manage its own lifetime.
It could be used to implement a nasty, intrusive reference-counting scheme. You would have functions to "acquire" a reference to the object, preventing it from being deleted, and then "release" it once you've finished, deleting it if noone else has acquired it, along the lines of:
class Nasty {
public:
Nasty() : references(1) {}
void acquire() {
++references;
}
void release() {
if (--references == 0) {
delete this;
}
}
private:
~Nasty() {}
size_t references;
};
// Usage
Nasty * nasty = new Nasty; // 1 reference
nasty->acquire(); // get a second reference
nasty->release(); // back to one
nasty->release(); // deleted
nasty->acquire(); // BOOM!
I would prefer to use std::shared_ptr for this purpose, since it's thread-safe, exception-safe, works for any type without needing any explicit support, and prevents access after deleting.
More usefully, it could be used in an event-driven system, where objects are created, and then manage themselves until they receive an event that tells them that they're no longer needed:
class Worker : EventReceiver {
public:
Worker() {
start_receiving_events(this);
}
virtual void on(WorkEvent) {
do_work();
}
virtual void on(DeleteEvent) {
stop_receiving_events(this);
delete this;
}
private:
~Worker() {}
void do_work();
};
1) Why would I want to force the object to be made on the heap instead of on the stack?
1) Because the object's lifetime is not logically tied to a scope (e.g., function body, etc.). Either because it must manage its own lifespan, or because it is inherently a shared object (and thus, its lifespan must be attached to those of its co-dependent objects). Some people here have pointed out some examples like event handlers, task objects (in a scheduler), and just general objects in a complex object hierarchy.
2) Because you want to control the exact location where code is executed for the allocation / deallocation and construction / destruction. The typical use-case here is that of cross-module code (spread across executables and DLLs (or .so files)). Because of issues of binary compatibility and separate heaps between modules, it is often a requirement that you strictly control in what module these allocation-construction operations happen. And that implies the use of heap-based objects only.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Well, your use-case is really just a "how-to" not a "why". Of course, if you are going to use a delete this; statement within a member function, then you must have controls in place to force all creations to occur with new (and in the same translation unit as the delete this; statement occurs). Not doing this would just be very very poor style and dangerous. But that doesn't address the "why" you would use this.
1) As others have pointed out, one legitimate use-case is where you have an object that can determine when its job is over and consequently destroy itself. For example, an event handler deleting itself when the event has been handled, a network communication object that deletes itself once the transaction it was appointed to do is over, or a task object in a scheduler deleting itself when the task is done. However, this leaves a big problem: signaling to the outside world that it no longer exists. That's why many have mentioned the "intrusive reference counting" scheme, which is one way to ensure that the object is only deleted when there are no more references to it. Another solution is to use a global (singleton-like) repository of "valid" objects, in which case any accesses to the object must go through a check in the repository and the object must also add/remove itself from the repository at the same time as it makes the new and delete this; calls (either as part of an overloaded new/delete, or alongside every new/delete calls).
However, there is a much simpler and less intrusive way to achieve the same behavior, albeit less economical. One can use a self-referencing shared_ptr scheme. As so:
class AutonomousObject {
private:
std::shared_ptr<AutonomousObject> m_shared_this;
protected:
AutonomousObject(/* some params */);
public:
virtual ~AutonomousObject() { };
template <typename... Args>
static std::weak_ptr<AutonomousObject> Create(Args&&... args) {
std::shared_ptr<AutonomousObject> result(new AutonomousObject(std::forward<Args>(args)...));
result->m_shared_this = result; // link the self-reference.
return result; // return a weak-pointer.
};
// this is the function called when the life-time should be terminated:
void OnTerminate() {
m_shared_this.reset( NULL ); // do not use reset(), but use reset( NULL ).
};
};
With the above (or some variations upon this crude example, depending on your needs), the object will be alive for as long as it deems necessary and that no-one else is using it. The weak-pointer mechanism serves as the proxy to query for the existence of the object, by possible outside users of the object. This scheme makes the object a bit heavier (has a shared-pointer in it) but it is easier and safer to implement. Of course, you have to make sure that the object eventually deletes itself, but that's a given in this kind of scenario.
2) The second use-case I can think of ties in to the second motivation for restricting an object to be heap-only (see above), however, it applies also for when you don't restrict it as such. If you want to make sure that both the deallocation and the destruction are dispatched to the correct module (the module from which the object was allocated and constructed), you must use a dynamic dispatching method. And for that, the easiest is to just use a virtual function. However, a virtual destructor is not going to cut it because it only dispatches the destruction, not the deallocation. The solution is to use a virtual "destroy" function that calls delete this; on the object in question. Here is a simple scheme to achieve this:
struct CrossModuleDeleter; //forward-declare.
class CrossModuleObject {
private:
virtual void Destroy() /* final */;
public:
CrossModuleObject(/* some params */); //constructor can be public.
virtual ~CrossModuleObject() { }; //destructor can be public.
//.... whatever...
friend struct CrossModuleDeleter;
template <typename... Args>
static std::shared_ptr< CrossModuleObject > Create(Args&&... args);
};
struct CrossModuleDeleter {
void operator()(CrossModuleObject* p) const {
p->Destroy(); // do a virtual dispatch to reach the correct deallocator.
};
};
// In the cpp file:
// Note: This function should not be inlined, so stash it into a cpp file.
void CrossModuleObject::Destroy() {
delete this;
};
template <typename... Args>
std::shared_ptr< CrossModuleObject > CrossModuleObject::Create(Args&&... args) {
return std::shared_ptr< CrossModuleObject >( new CrossModuleObject(std::forward<Args>(args)...), CrossModuleDeleter() );
};
The above kind of scheme works well in practice, and it has the nice advantage that the class can act as a base-class with no additional intrusion by this virtual-destroy mechanism in the derived classes. And, you can also modify it for the purpose of allowing only heap-based objects (as usually, making constructors-destructors private or protected). Without the heap-based restriction, the advantage is that you can still use the object as a local variable or data member (by value) if you want, but, of course, there will be loop-holes left to avoid by whoever uses the class.
As far as I know, these are the only legitimate use-cases I have ever seen anywhere or heard of (and the first one is easily avoidable, as I have shown, and often should be).
The general reason is that the lifetime of the object is determined by some factor internal to the class, at least from an application viewpoint. Hence, it may very well be a private method which calls delete this;.
Obviously, when the object is the only one to know how long it's needed, you can't put it on a random thread stack. It's necessary to create such objects on the heap.
It's generally an exceptionally bad idea. There are a very few cases- for example, COM objects have enforced intrusive reference counting. You'd only ever do this with a very specific situational reason- never for a general-purpose class.
1) Why would I want to force the object to be made on the heap instead of on the stack?
Because its life span isn't determined by the scoping rule.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
You use delete this when the object is the best placed one to be responsible for its own life span. One of the simplest example I know of is a window in a GUI. The window reacts to events, a subset of which means that the window has to be closed and thus deleted. In the event handler the window does a delete this. (You may delegate the handling to a controller class. But the situation "window forwards event to controller class which decides to delete the window" isn't much different of delete this, the window event handler will be left with the window deleted. You may also need to decouple the close from the delete, but your rationale won't be related to the desirability of delete this).
delete this;
can be useful at times and is usually used for a control class that also controls the lifetime of another object. With intrusive reference counting, the class it is controlling is one that derives from it.
The outcome of using such a class should be to make lifetime handling easier for users or creators of your class. If it doesn't achieve this, it is bad practice.
A legitimate example may be where you need a class to clean up all references to itself before it is destructed. In such a case, you "tell" the class whenever you are storing a reference to it (in your model, presumably) and then on exit, your class goes around nulling out these references or whatever before it calls delete this on itself.
This should all happen "behind the scenes" for users of your class.
"Why would I want to force the object to be made on the heap instead of on the stack?"
Generally when you force that it's not because you want to as such, it's because the class is part of some polymorphic hierarchy, and the only legitimate way to get one is from a factory function that returns an instance of a different derived class according to the parameters you pass it, or according to some configuration that it knows about. Then it's easy to arrange that the factory function creates them with new. There's no way that users of those classes could have them on the stack even if they wanted to, because they don't know in advance the derived type of the object they're using, only the base type.
Once you have objects like that, you know that they're destroyed with delete, and you can consider managing their lifecycle in a way that ultimately ends in delete this. You'd only do this if the object is somehow capable of knowing when it's no longer needed, which usually would be (as Mike says) because it's part of some framework that doesn't manage object lifetime explicitly, but does tell its components that they've been detached/deregistered/whatever[*].
If I remember correctly, James Kanze is your man for this. I may have misremembered, but I think he occasionally mentions that in his designs delete this isn't just used but is common. Such designs avoid shared ownership and external lifecycle management, in favour of networks of entity objects managing their own lifecycles. And where necessary, deregistering themselves from anything that knows about them prior to destroying themselves. So if you have several "tools" in a "toolbelt" then you wouldn't construe that as the toolbelt "owning" references to each of the tools, you think of the tools putting themselves in and out of the belt.
[*] Otherwise you'd have your factory return a unique_ptr or auto_ptr to encourage callers to stuff the object straight into the memory management type of their choice, or you'd return a raw pointer but provide the same encouragement via documentation. All the stuff you're used to seeing.
A good rule of thumb is not to use delete this.
Simply put, the thing that uses new should be responsible enough to use the delete when done with the object. This also avoids the problems with is on the stack/heap.
Once upon a time i was writing some plugin code. I believe i mixed build (debug for plugin, release for main code or maybe the other way around) because one part should be fast. Or maybe another situation happened. Such main is already released built on gcc and plugin is being debugged/tested on VC. When the main code deleted something from the plugin or plugin deleted something a memory issue would occur. It was because they both used different memory pools or malloc implementations. So i had a private dtor and a virtual function called deleteThis().
-edit- Now i may consider overloading the delete operator or using a smart pointer or simply just state never delete a function. It will depend and usually overloading new/delete should never be done unless you really know what your doing (dont do it). I decide to use deleteThis() because i found it easier then the C like way of thing_alloc and thing_free as deleteThis() felt like the more OOP way of doing it

Best practice when calling initialize functions multiple times?

This may be a subjective question, but I'm more or less asking it and hoping that people share their experiences. (As that is the biggest thing which I lack in C++)
Anyways, suppose I have -for some obscure reason- an initialize function that initializes a datastructure from the heap:
void initialize() {
initialized = true;
pointer = new T;
}
now When I would call the initialize function twice, an memory leak would happen (right?). So I can prevent this is multiple ways:
ignore the call (just check wether I am initialized, and if I am don't do anything)
Throw an error
automatically "cleanup" the code and then reinitialize the thing.
Now what is generally the "best" method, which helps keeping my code manegeable in the future?
EDIT: thank you for the answers so far. However I'd like to know how people handle this is a more generic way. - How do people handle "simple" errors which can be ignored. (like, calling the same function twice while only 1 time it makes sense).
You're the only one who can truly answer the question : do you consider that the initialize function could eventually be called twice, or would this mean that your program followed an unexpected execution flow ?
If the initialize function can be called multiple times : just ignore the call by testing if the allocation has already taken place.
If the initialize function has no decent reason to be called several times : I believe that would be a good candidate for an exception.
Just to be clear, I don't believe cleanup and regenerate to be a viable option (or you should seriously consider renaming the function to reflect this behavior).
This pattern is not unusual for on-demand or lazy initialization of costly data structures that might not always be needed. Singleton is one example, or for a class data member that meets those criteria.
What I would do is just skip the init code if the struct is already in place.
void initialize() {
if (!initialized)
{
initialized = true;
pointer = new T;
}
}
If your program has multiple threads you would have to include locking to make this thread-safe.
I'd look at using boost or STL smart pointers.
I think the answer depends entirely on T (and other members of this class). If they are lightweight and there is no side-effect of re-creating a new one, then by all means cleanup and re-create (but use smart pointers). If on the other hand they are heavy (say a network connection or something like that), you should simply bypass if the boolean is set...
You should also investigate boost::optional, this way you don't need an overall flag, and for each object that should exist, you can check to see if instantiated and then instantiate as necessary... (say in the first pass, some construct okay, but some fail..)
The idea of setting a data member later than the constructor is quite common, so don't worry you're definitely not the first one with this issue.
There are two typical use cases:
On demand / Lazy instantiation: if you're not sure it will be used and it's costly to create, then better NOT to initialize it in the constructor
Caching data: to cache the result of a potentially expensive operation so that subsequent calls need not compute it once again
You are in the "Lazy" category, in which case the simpler way is to use a flag or a nullable value:
flag + value combination: reuse of existing class without heap allocation, however this requires default construction
smart pointer: this bypass the default construction issue, at the cost of heap allocation. Check the copy semantics you need...
boost::optional<T>: similar to a pointer, but with deep copy semantics and no heap allocation. Requires the type to be fully defined though, so heavier on dependencies.
I would strongly recommend the boost::optional<T> idiom, or if you wish to provide dependency insulation you might fall back to a smart pointer like std::unique_ptr<T> (or boost::scoped_ptr<T> if you do not have access to a C++0x compiler).
I think that this could be a scenario where the Singleton pattern could be applied.