Thread: Smart Pointers

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Smart pointers are how C++ exemplifies ownership of data and its lifetime.

    unique_ptrs are sole owners of a piece of data whose lifetime is that of the unique_ptr itself. So if you have a unique_ptr to an allocation, the allocation is deallocated when the unique_ptr dies.

    shared_ptrs represent shared ownership of a piece of data. The data lives as long as the last remaining smart_ptr does. This allows you to manage data across something like threads. By returning shared_ptrs to data, you can safely ensure that it'll eventually be freed even when your code has a large degree of asynchronousness.

    weak_ptrs don't claim ownership of a piece of data until you attempt to access it in which case, it has a method that creates a shared_ptr for you to access the data with. It's a neat little tool. More info here: std::weak_ptr - cppreference.com

    I'm not sure about the last one. But yeah, you can look up things like shared_ptr circular references and the resulting memory leaks and that'll give you an idea of why graph-based structures benefit from a combination of shared and weak pointers.

    This is a good link too: Smart pointer - Wikipedia
    Last edited by MutantJohn; 01-11-2017 at 10:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Smart Pointers
    By cmajor28 in forum C++ Programming
    Replies: 17
    Last Post: 05-10-2015, 12:01 PM
  2. When to use smart pointers?
    By Neo1 in forum C++ Programming
    Replies: 1
    Last Post: 04-15-2012, 10:53 AM
  3. unsure about auto/smart pointers
    By l2u in forum C++ Programming
    Replies: 16
    Last Post: 07-13-2007, 12:55 PM
  4. weak pointers and use_count smart pointers
    By Mario F. in forum C++ Programming
    Replies: 2
    Last Post: 07-29-2006, 07:54 AM
  5. Use Count smart pointers. Need clarification
    By Mario F. in forum C++ Programming
    Replies: 8
    Last Post: 06-26-2006, 03:07 PM

Tags for this Thread