Why am I allowed to copy unique_ptr? [duplicate]

Digital Marketing Facebook Marketing API 3 years ago

6.66K 2 0 0 0

_x000D_ _x000D_ Possible Duplicate: Returning unique_ptr from functions 20.7.1.2 [unique.ptr.single] defines copy constructor like this : // disable copy from lvalue unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; So, why the following code compiles fine? #include #include std::unique_ptr< int > bar() { std::unique_ptr< int > p( new int(4)); return p; } int main() { auto p = bar(); std::cout<<*p<

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 years ago
_x000D_ In the return statement, if you return a local variable, the expression is treated as an rvalue, and thus automatically moved. It is thus similar to: return std::move(p); It invokes the unique_ptr(unique_ptr&&) constructor. In the main function, bar() produces a temporary, which is an rvalue, and is also properly moved into the p in main.
0 views
0 shares

profilepic.png
xiaohuilang 4 months ago
temporary
0 views   0 shares

No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Similar Forum


Q

What are the best SEO tools for a personal website? What website or tools should I use to build and...

What are the best SEO tools for a personal website? What website or tools should I use to build and...
Q

Why is keyword research important?

Why is keyword research important?
Q

What is SEO ?

What is SEO ?