Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Smart pointer
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== unique_ptr == [[C++11]] introduces {{code|std::unique_ptr}}, defined in the header {{code|<memory>}}.<ref name="ISO14882_2011"/> A {{code|unique_ptr}} is a container for a raw pointer, which the <code>unique_ptr</code> is said to own. A <code>unique_ptr</code> explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the {{code|std::move}} function can be used to transfer ownership of the contained pointer to another {{code|unique_ptr}}. A <code>unique_ptr</code> cannot be copied because its copy constructor and assignment operators are explicitly deleted. <syntaxhighlight lang="cpp"> std::unique_ptr<int> p1(new int(5)); std::unique_ptr<int> p2 = p1; // Compile error. std::unique_ptr<int> p3 = std::move(p1); // Transfers ownership. p3 now owns the memory and p1 is set to nullptr. p3.reset(); // Deletes the memory. p1.reset(); // Does nothing. </syntaxhighlight> <code>std::[[auto_ptr]]</code> is [[Deprecation|deprecated]] under C++11 and completely removed from [[C++17]]. The copy constructor and assignment operators of {{code|auto_ptr}} do not actually copy the stored pointer. Instead, they [[Auto ptr#Semantics|transfer it]], leaving the prior {{code|auto_ptr}} object empty. This was one way to implement strict ownership, so that only one {{code|auto_ptr}} object can own the pointer at any given time. This means that {{code|auto_ptr}} should not be used where copy semantics are needed.<ref name="CERT"/>{{citation needed|date=September 2016}} Since {{code|auto_ptr}} already existed with its copy semantics, it could not be upgraded to be a move-only pointer without breaking [[backward compatibility]] with existing code.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)