I learned that unique pointers "die" at the end of a scope. So how does it work in class members? Does shared pointers work?
I learned that unique pointers "die" at the end of a scope. So how does it work in class members? Does shared pointers work?
Yes absolutely! You can use them in classes as members.
When its used as a member variable, the lifetime of the unique pointer is the lifetime of the object itself (unless you explicitly release them). When the object is destructed, the unique pointer and all the smart pointers will deallocate its memory.
Can I use smart pointers as class members in C++?
Yes. Pretty much any class can be a member except for classes that cannot be instantiated at all.
I learned that unique pointers "die" at the end of a scope.
All automatic variables "die" at the end of scope. This property is not particular to smart pointers. Example:
{
int i = 42;
} // i "dies" here
A thing that makes smart pointers different from bare pointers is not that they "die" at the end of scope (because bare pointers also "die"), but rather what the smart pointers do when they "die".
A non-static member varible "dies" when the super object "dies".
Does shared pointers work?
Yes.