Kathick
Kathick

Reputation: 1405

understanding the smart pointer boost in c++

I am new to c++ as well as smart pointer. I have a code like this.

Example* Example::get_instance() {
        Example* example = new Example();
        return example;
}

I am trying to convert it to smart pointer like this

shared_ptr<Example> Example::get_instance() {
        shared_ptr<Example> example (new Example());
        return example;
}

Is this the correct way because when i am trying to call this from another class its not working.I am trying to implement a singleton object.

Upvotes: 2

Views: 376

Answers (1)

Ed Barbu
Ed Barbu

Reputation: 1639

You are creating a new Example object every time the object is requested, That is a memory leak, an you are also returning a different object every time. Try this instead:

Example & Example::get_instance() {
        static Example example;
        return example;
}

Also please note the following advices for your code:

  • when creating smart pointers prefer make_shared instead of shared_ptr<YourType>(new YourType(...)). The reason why can be found here. Relevant excerpt:

    This function typically allocates memory for the T object and for the shared_ptr's control block with a single memory allocation (it is a non-binding requirement in the Standard). In contrast, the declaration std::shared_ptr p(new T(Args...)) performs at least two memory allocations, which may incur unnecessary overhead. Moreover, f(shared_ptr(new int(42)), g()) can lead to memory leak if g throws an exception. This problem doesn't exist if make_shared is used.

  • understand the difference between std::unique_ptr and std::shared_ptr. For your case, a std::unique_ptr would have been better, but there is an even simpler solution to your problem, which I have shown above.

  • in general, avoid pointers when you can use references instead, they're easier to use and code looks a bit cleaner.

  • and finally, do you REALLY want a singleton? I just have to be ask. I've been working full-time as a programmer for almost 4 years now. Not that long, I know, but enough to have encountered the situation where I regretted that I or someone else used the Singleton pattern instead of passing the reference to my object down the call chain.

Try to avoid singletons, you may later find your code using the singleton might in the end want to work on multiple instances of your Example object instead of calling Example::get_instance and only work on that single instances. So when you'll have that revelation, (and it might be only a matter of time), you'll have major refactoring ahead of you.

So, "Beware, there be dragons!".

Upvotes: 1

Related Questions