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
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.
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