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
71
votes
3 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
  • 228,013
  • 71
  • 433
  • 510
70
votes
1 answer

"Downcasting" unique_ptr to unique_ptr

I have a series of factories that return unique_ptr. Under the hood, though, they are providing pointers to various derived types, i.e unique_ptr, unique_ptr, unique_ptretc. Given DerivedA : Derived and Derived :…
d7samurai
  • 3,086
  • 2
  • 30
  • 43
66
votes
3 answers

Getting a normal ptr from boost::shared_ptr?

I have something like boost::shared_ptr t(makeSomething(), mem_fun(&Type::deleteMe)) I now need to call C styled function that requires a pointer to Type. How do I get it from boost::shared_ptr?
user34537
61
votes
3 answers

C++11: Replace all non-owning raw pointers with std::shared_ptr()?

With the advent of std::unique_ptr, the blemished std::auto_ptr can finally be put to rest. So for the last several days, I have been changing my code to use smart pointers and to eliminate all delete from my code. Although valgrind says my code is…
kfmfe04
  • 14,936
  • 14
  • 74
  • 140
61
votes
2 answers

smart pointers and arrays

How do smart pointers handle arrays? For example, void function(void) { std::unique_ptr my_array(new int[5]); } When my_array goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of…
helloworld922
  • 10,801
  • 5
  • 48
  • 85
59
votes
2 answers

How to get the Object being pointed by a shared pointer?

I have a query. Can we get the object that a shared pointer points to directly? Or should we get the underlying RAW pointer through get() call and then access the corresponding object?
Pavan Dittakavi
  • 3,013
  • 5
  • 27
  • 47
58
votes
9 answers

Smart pointers/safe memory management for C?

I, and I think many others, have had great success using smart pointers to wrap up unsafe memory operations in C++, using things like RAII, et cetera. However, wrapping memory management is easier to implement when you have destructors, classes,…
mannicken
  • 6,885
  • 4
  • 31
  • 38
57
votes
4 answers

creating a shared_ptr from unique_ptr

In a piece of code I reviewed lately, which compiled fine with g++-4.6, I encountered a strange try to create a std::shared_ptr from std::unique_ptr: std::unique_ptr foo... std::make_shared(std::move(foo)); This seems rather odd to me.…
stefan
  • 10,215
  • 4
  • 49
  • 90
56
votes
9 answers

Dynamic casting for unique_ptr

As it was the case in Boost, C++11 provides some functions for casting shared_ptr: std::static_pointer_cast std::dynamic_pointer_cast std::const_pointer_cast I am wondering, however, why there are no equivalents functions for unique_ptr. Consider…
betabandido
  • 18,946
  • 11
  • 62
  • 76
53
votes
5 answers

Can Google Mock a method with a smart pointer return type?

I have a factory that returns a smart pointer. Regardless of what smart pointer I use, I can't get Google Mock to mock the factory method. The mock object is the implementation of a pure abstract interface where all methods are virtual. I have a…
Matthew Reddington
  • 1,409
  • 3
  • 13
  • 24
52
votes
5 answers

How to pass deleter to make_shared?

Since C++11, because of several reasons, developers tend to use smart pointer classes for dynamic lifetime objects. And with those new smart pointer classes, standards, even suggest to not use operators like new instead they suggest to use…
cavitsinadogru
  • 940
  • 2
  • 10
  • 17
51
votes
9 answers

Use of observer_ptr

What exactly is the point of the construct std::observer_ptr in the library fundamentals technical specification V2? It seems to me that all it does is wrap a bare T*, which seems like a superfluous step if it adds no dynamic memory safety. In all…
RamblingMad
  • 5,332
  • 2
  • 24
  • 48
51
votes
1 answer

Recommended usage of std::unique_ptr

What are recommended uses of a std::unique_ptr as to specifically where, when, and how is it is best used? I discovered: About unique_ptr performances I already know: std::unique_ptr was developed in C++11 as a replacement for std::auto_ptr That…
Mushy
  • 2,535
  • 10
  • 33
  • 54
50
votes
6 answers

How to enable_shared_from_this of both parent and derived

I have simple base and derived class that I want both have shared_from_this(). This simple solution: class foo : public enable_shared_from_this { void foo_do_it() { cout<<"foo::do_it\n"; } public: virtual…
Artyom
  • 31,019
  • 21
  • 127
  • 215
49
votes
3 answers

Bad practice to return unique_ptr for raw pointer like ownership semantics?

I've written a static factory method that returns a new Foobar object populated from another data object. I've recently been obsessed with ownership semantics and am wondering if I'm conveying the right message by having this factory method return a…
Bret Kuhns
  • 4,034
  • 5
  • 31
  • 43