Reputation: 1405
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
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.
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