In C++, if I return a shared/unique ptr from a function, does it return by value? Ie
shared_ptr<CLASS> function_f(){
auto p = make_shared<CLASS>(5);
return p;
}
So what happens? Is the pointer inside dynamically allocated? If I return this, do I have 2 pointers pointing to the same thing?
The shared_ptr itself is returned by value. The CLASS object that it points to is dynamically allocated and therefore not copied.
You may briefly have two shared_ptrs to the same object (except for RVO, so in practice you probably won't), but by design of the shared_ptr class, this is not a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With