简体   繁体   中英

Returning a unique_ptr<T> . Concept clarification

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM