5

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

Community
  • 1
  • 1
MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 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 Answers1

13

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.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451