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

2763 questions
122
votes
11 answers

Smart pointers: who owns the object?

C++ is all about memory ownership - aka ownership semantics. It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory. In C++ ownership is documented…
Martin York
  • 257,169
  • 86
  • 333
  • 562
121
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
  • 7,930
  • 6
  • 36
  • 80
114
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
  • 37,137
  • 18
  • 79
  • 144
108
votes
4 answers

Where is shared_ptr?

I am so frustrated right now after several hours trying to find where shared_ptr is located. None of the examples I see show complete code to include the headers for shared_ptr (and working). Simply stating std, tr1 and is not helping at…
Jake
  • 11,273
  • 21
  • 90
  • 147
105
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
  • 5,379
  • 12
  • 43
  • 48
98
votes
3 answers

How is it possible (if it is) to implement shared_ptr without requiring polymorphic classes to have virtual destructor?

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
  • 130,161
  • 59
  • 324
  • 434
94
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
  • 4,081
  • 5
  • 30
  • 39
86
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
  • 26,717
  • 34
  • 141
  • 196
86
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
  • 15,455
  • 16
  • 74
  • 121
84
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,398
  • 12
  • 45
  • 64
83
votes
10 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,754
  • 2
  • 19
  • 35
80
votes
7 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
  • 56,458
  • 54
  • 195
  • 288
80
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,091
  • 2
  • 9
  • 14
80
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 kumar
  • 20,438
  • 23
  • 90
  • 126
73
votes
3 answers

std::shared_ptr initialization: make_shared() vs shared_ptr(new Foo)

What's the difference between: std::shared_ptr p = std::shared_ptr( new int ); and std::shared_ptr p = std::make_shared< int >(); ? Which one should I prefer and why? P. S. Pretty sure this must have been answered already, but I…
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335