I am learning C++. I just learned std::shared_ptr
can be used for managing heap-allocated object as in reference-counting manner.
Currently my compiler (Xcode/Clang/C++11) shows exact behavior what I wanted. Prints this result,
Step0
Step1
CREATED!
Step2
Step3
Step5
DESTROYED!
Step6
with this code.
class Obj1
{
public:
Obj1() { printf("CREATED!\n"); }
~Obj1() { printf("DESTROYED!\n"); }
};
std::shared_ptr<Obj1> func1 ()
{
printf("Step0\n");
{
printf("Step1\n");
std::shared_ptr<Obj1> o1(new Obj1());
printf("Step2\n");
std::shared_ptr<Obj1> o2 = o1;
printf("Step3\n");
return o2;
}
printf("Step4\n");
}
int main(int argc, const char * argv[])
{
{
std::shared_ptr<Obj1> o3 = func1();
printf("Step5\n");
}
printf("Step6\n");
return 0;
}
But as far as I know, this can be happen by C++'s copy constructor optimization when the std::shared_ptr
is assigned to new variable. (I am not sure the name...) If it is, the Obj1
instance maybe not guaranteed to be alive when it is being returned from the function, because actually the shared_ptr
is destroyed and re-creared at caller semantically.
Of course all these are newbie's assumption. Please let me know what actually expected on object lifetime in this case.
PS. This is derived from my previous question: Good practice or convention for cleanup heap allocated object?
Either o2
's lifetime is extended or a copy of it is made before it's destroyed. Either way, at least one shared_ptr
always exists, so the code is safe.