The term "correct" is quite vague. Ok, this code should work, if you ask of that. However there are more details you should take into consideration.
First, it is better to construct the object in the same expression where you construct the smart pointer:
std::shared_ptr<Geometry> Clone() const
{
return std::shared_ptr< Geometry >(new Circle(*this));
}
Why so? Imagine that you add one more line of code in between, and this code throws an exception... That is the benefit of smart pointers that they prevent you from memory leaks like that, and you loose this benefit in your initial version of code.
Next, I don't see the definition of the class Geometry
, and it probably has a virtual destructor... But what if it doesn't? Which class would the shared_ptr destroy? The answer is: the class that shared_ptr knows. Ok, in your code there is a way for shared_ptr to get known that the actual class is class Circle
(because of the shared_ptr constructor, that knows exactly the actual class of the underlying object), but it is very easy to make a mistake. One-liner solves this issue.
But there is one more (possible) improvement: std::make_shared
:
std::shared_ptr<Geometry> Clone() const
{
return std::make_shared< Circle >(*this);
}
In this case you allocate memory only once, for both the object and the counter structure. That works better unless you employ std::weak_ptr
. You should be very careful using both std::make_shared
and std:weak_ptr
: the actual memory deallocation of the shared counter (which is the same memory that is used for the object itself in case of std::make_shared
) will be done only after the last weak_ptr is destroyed. That could cause some sort of a memory leak.
So the way you use it is correct, but there is not enough information to judge what is the best idiomatic way to do that.