Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a shared pointer

Tags:

c++

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?

like image 638
Bana Avatar asked Oct 24 '25 18:10

Bana


1 Answers

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.

like image 119
Thomas Avatar answered Oct 26 '25 08:10

Thomas