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!
== Features == In [[C++]], a smart pointer is implemented as a template class that mimics, by means of [[operator overloading]], the behaviors of a traditional [[Raw pointer|(raw) pointer]], (e.g. dereferencing, assignment) while providing additional memory management features. Smart pointers can facilitate intentional programming by expressing, in the type, how the memory of the referent of the pointer will be managed. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory of the referent when the caller is finished with the information. <syntaxhighlight lang="cpp"> SomeType* AmbiguousFunction(); // What should be done with the result? </syntaxhighlight> Traditionally, naming conventions have been used to resolve the ambiguity,<ref name="Taligent"/> which is an error-prone, labor-intensive approach. [[C++11]] introduced a way to ensure correct memory management in this case by declaring the function to return a <code>unique_ptr</code>, <syntaxhighlight lang="cpp"> std::unique_ptr<SomeType> ObviousFunction(); </syntaxhighlight> The declaration of the function return type as a <code>unique_ptr</code> makes explicit the fact that the caller takes ownership of the result, and the C++ runtime ensures that the memory will be reclaimed automatically. Before [[C++11]], unique_ptr can be replaced with [[auto_ptr]], which is now deprecated.
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)