Questions tagged [smart-pointers]

An abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking

Smart pointers are objects that look and feel like pointers, but are smarter.

What does this mean? To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->). An object that looks and feels like something else is called a proxy object, or just proxy. The proxy pattern and its many uses are described in the books Design Patterns and Pattern Oriented Software Architecture.

To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things can save a lot of aspirin...

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library (C++03). You can find it in the header <memory>, or take a look at Scott Meyers' auto_ptr implementation. Here is the relevant parts of auto_ptr's implementation, to illustrate what it does:

template <class T> class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}
    T* operator->()             {return ptr;}
    // ...
};

As shown, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its "smartness" is in the destructor: the destructor takes care of deleting the pointer.

For the user of auto_ptr, this means that instead of writing:

void foo()
{
    MyClass* p(new MyClass);
    p->DoSomething();
    delete p;
}

You can write:

void foo()
{
    auto_ptr<MyClass> p(new MyClass);
    p->DoSomething();
}

And trust p to clean-up after itself.

Smart pointers form part of the idiomatic RAII (Resource Acquisition Is Initialisation) technique that is core to resource management in C++.

Links:

http://ootips.org/yonat/4dev/smart-pointers.html

2412 questions
107
votes
2 answers

Why is shared_ptr legal, while unique_ptr is ill-formed?

The question really fits in the title: I am curious to know what is the technical reason for this difference, but also the rationale ? std::shared_ptr sharedToVoid; // legal; std::unique_ptr uniqueToVoid; // ill-formed;
Ad N
  • 6,830
  • 4
  • 28
  • 65
106
votes
2 answers

How to return smart pointers (shared_ptr), by reference or by value?

Let's say I have a class with a method that returns a shared_ptr. What are the possible benefits and drawbacks of returning it by reference or by value? Two possible clues: Early object destruction. If I return the shared_ptr by (const) reference,…
Vincenzo Pii
  • 16,001
  • 8
  • 35
  • 48
99
votes
4 answers

Passing shared_ptr as shared_ptr

What is the best method to go about passing a shared_ptr of a derived type to a function that takes a shared_ptr of a base type? I generally pass shared_ptrs by reference to avoid a needless copy: int foo(const shared_ptr& ptr); but this…
Matt Kline
  • 9,013
  • 3
  • 44
  • 76
98
votes
5 answers

Why is auto_ptr being deprecated?

I heard auto_ptr is being deprecated in C++11. What is the reason for this? Also I would like to know the difference between auto_ptr and shared_ptr.
brett
  • 4,759
  • 11
  • 38
  • 44
95
votes
5 answers

Is there a non-atomic equivalent of std::shared_ptr? And why isn't there one in ?

This is a bit of a two part question, all about the atomicity of std::shared_ptr: 1. As far as I can tell, std::shared_ptr is the only smart pointer in that's atomic. I'm wondering if there is a non-atomic version of std::shared_ptr…
Cornstalks
  • 34,193
  • 13
  • 69
  • 132
92
votes
3 answers

shared_ptr magic :)

Mr. Lidström and I had an argument :) Mr. Lidström's claim is that a construct shared_ptr p(new Derived); doesn't require Base to have a virtual destructor: Armen Tsirunyan: "Really? Will the shared_ptr clean up correctly? Could you please in…
Armen Tsirunyan
  • 120,726
  • 52
  • 304
  • 418
84
votes
4 answers

Is auto_ptr deprecated?

Will auto_ptr be deprecated in incoming C++ standard? Should unique_ptr be used for ownership transfer instead of shared_ptr? If unique_ptr is not in the standard, then do I need to use shared_ptr instead?
dimba
  • 24,103
  • 28
  • 127
  • 188
82
votes
7 answers

Example to use shared_ptr?

Hi I asked a question today about How to insert different types of objects in the same vector array and my code in that question was gate* G[1000]; G[0] = new ANDgate() ; G[1] = new ORgate; //gate is a class inherited by ANDgate and ORgate…
Ahmed
  • 3,258
  • 11
  • 40
  • 61
79
votes
10 answers

When to use shared_ptr and when to use raw pointers?

class B; class A { public: A () : m_b(new B()) { } shared_ptr GimmeB () { return m_b; } private: shared_ptr m_b; }; Let's say B is a class that semantically should not exist outside of the…
TripShock
  • 3,702
  • 4
  • 25
  • 37
78
votes
12 answers

RAII vs. Garbage Collector

I recently watched a great talk by Herb Sutter about "Leak Free C++..." at CppCon 2016 where he talked about using smart pointers to implement RAII (Resource acquisition is initialization) - Concepts and how they solve most of the memory leaks…
Jiddoo
  • 1,043
  • 1
  • 8
  • 13
75
votes
7 answers

How can I use covariant return types with smart pointers?

I have code like this: class RetInterface {...} class Ret1: public RetInterface {...} class AInterface { public: virtual boost::shared_ptr get_r() const = 0; ... }; class A1: public AInterface { public: …
amit
  • 19,082
  • 22
  • 86
  • 126
72
votes
2 answers

Should I assign or reset a unique_ptr?

Given the common situation where the lifespan of an owned object is linked to its owner, I can use a unique pointer one of 2 ways . . It can be assigned: class owner { std::unique_ptr owned; public: owner() { …
learnvst
  • 13,927
  • 13
  • 65
  • 108
65
votes
2 answers

Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't?

The std::unique_ptr template has two parameters: the type of the pointee, and the type of the deleter. This second parameter has a default value, so you usually just write something like std::unique_ptr. The std::shared_ptr template has only…
R. Martinho Fernandes
  • 209,766
  • 68
  • 412
  • 492
65
votes
7 answers

Why can't a weak_ptr be constructed from a unique_ptr?

If I understand correctly, a weak_ptr doesn't increment the reference count of the managed object, therefore it doesn't represent ownership. It simply lets you access an object, the lifetime of which is managed by someone else. So I don't really see…
notadam
  • 2,494
  • 2
  • 16
  • 30
63
votes
8 answers

When should I use raw pointers over smart pointers?

After reading this answer, it looks like it is a best practice to use smart pointers as much as possible, and to reduce the usage of "normal"/raw pointers to minimum. Is that true?
Alon Gubkin
  • 53,054
  • 52
  • 181
  • 282