While reading about boost unique_ptr and on this link it states that such a pointer cannot be copied which I understand however it states that such a pointer can be returned from a function. This raises a question in my mind when something is returned from a function (not as a reference or a pointer) the copy constructor is called.So does this mean that unique ptr does not work with the assignment operator and works with a copy constructor (such that only ptr points to an object at a time) Also does it have less of an overhead than boost a shared_ptr ? I am using VS2010
-
1"However, unique_ptr can be moved using the new move semantics". You should look into rvalue references in general and move semantics in particular. – Dave Jun 03 '13 at 21:05
-
possible duplicate of [Returning unique\_ptr from functions](http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions) – Praetorian Jun 03 '13 at 21:14
1 Answers
when something is returned from a function (not as a reference or a pointer) the copy constructor is called. [...]
Not necessarily. In C++11, the copy constructor is picked only if a move constructor is not present. In the absence of a move constructor, what would normally be a move (e.g. upon returning by value from a function) decays to a copy.
unique_ptr
has a move constructor, which means a unique_ptr
can be returned by value from a function.
Also does it have less of an overhead than boost a shared_ptr ?
That's an unrelated question, but yes, it does have less overhead. In fact, unique_ptr
is designed to be a zero-overhead RAII wrapper of a raw pointer that realizes unique ownership. Using a unique_ptr
does not cause any loss in terms of performance nor in terms of memory consumption with respect to the use of a raw pointer.

- 124,023
- 23
- 387
- 451
-
The second part is perfect. Could you explain the first part in terms of C++0x – MistyD Jun 03 '13 at 21:10
-
@MistyD: There is no "C++0x". C++0x is the name C++11 had before it was known that the Standard would be finalized in 2011 – Andy Prowl Jun 03 '13 at 21:11
-
-
@MistyD: In C++98 there were no move semantics, so you couldn't return by value something that is non-copyable – Andy Prowl Jun 03 '13 at 21:12
-
-
1@MistyD: Yes, a `unique_ptr` cannot be returned by value in C++98. Also notice, that there was no `std::unique_ptr` in C++98. – Andy Prowl Jun 03 '13 at 21:14
-
Oh thanks. I thought Boost had an implementation turns out I was wrong. Will mark this as answer after timer – MistyD Jun 03 '13 at 21:15
-
@MistyD: Boost has `scoped_ptr`, but in C++98 you cannot return it by value, since it's non-copyable – Andy Prowl Jun 03 '13 at 21:16
-
-
1Should we have something in the first paragraph about the returned thing being local to the function? – aschepler Jun 04 '13 at 00:17
-
@aschepler: I would be glad to improve my answer, but I'm not sure I understand what you mean. Could you please elaborate a bit? – Andy Prowl Jun 04 '13 at 07:47