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
29
votes
1 answer

C++11 Smart Pointer Policies

As I understand it, in the current specification of C++11, one should use: std::unique_ptr<> for one owner (most of the time) std::shared_ptr<> only when there are multiple owners in acyclic structure std::weak_ptr<> sparingly only when there are…
kfmfe04
  • 14,936
  • 14
  • 74
  • 140
29
votes
4 answers

boost Shared_pointer NULL

I'm using reset() as a default value for my shared_pointer (equivalent to a NULL). But how do I check if the shared_pointer is NULL? Will this return the right value ? boost::shared_ptr blah; blah.reset() if (blah == NULL) { //Does this…
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
29
votes
1 answer

enable_shared_from_this and inheritance

I've got a type which inherits from enable_shared_from_this, and another type that inherits from this type. Now I can't use the shared_from_this method because it returns the base type and in a specific derived class method I need the derived…
Puppy
  • 144,682
  • 38
  • 256
  • 465
29
votes
4 answers

What is the difference between std::shared_ptr and std::experimental::atomic_shared_ptr?

I read the following article by Antony Williams and as I understood in addition to the atomic shared count in std::shared_ptr in std::experimental::atomic_shared_ptr the actual pointer to the shared object is also atomic? But when I read about…
bobeff
  • 3,543
  • 3
  • 34
  • 62
29
votes
5 answers

Should I use shared_ptr or unique_ptr?

I have a question about std::unique_ptr and std::shared_ptr. I know there are loads of questions about when to use which one, but I'm still not sure if I understand it correctly. I read somewhere that the default choice for smart pointer should be…
dziwna
  • 1,212
  • 2
  • 14
  • 25
28
votes
2 answers

Does C++11 have wrappers for dynamically-allocated arrays like Boost's scoped_array?

I often need to deal with dynamically-allocated arrays in C++, and hence rely on Boost for scoped_array, shared_array, and the like. After reading through Stroustrup's C++11 FAQ and the C++11 Reference Wiki, I could not find a suitable replacement…
void-pointer
  • 14,247
  • 11
  • 43
  • 61
28
votes
4 answers

How can unique_ptr have no overhead if it needs to store the deleter?

First take a look at what C++ Primer said about unique_ptr and shared_ptr: $16.1.6. Efficiency and Flexibility We can be certain that shared_ptr does not hold the deleter as a direct member, because the type of the deleter isn’t known until run…
choxsword
  • 3,187
  • 18
  • 44
28
votes
3 answers

Smart pointers and parameter list allocation rules

An MSDN page about smart pointers includes a promoted warning about creating smart pointers in parameter lists: Always create smart pointers on a separate line of code, never in a parameter list, so that a subtle resource leak won’t occur due to…
fo_
  • 872
  • 8
  • 8
28
votes
4 answers

How do I pass smart pointers into functions?

When passing objects into functions, do the same rules apply to smart pointers as to other objects that contain dynamic memory? When I pass, for example, a std::vector into a function I always consider the following options: I'm…
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
27
votes
3 answers

Member function call on shared_ptr through member function pointer in template

This is a template function that takes a pointer (or a pointer like object) and a member function: template int example(Ptr ptr, MemberFunctor func ) { return (ptr->*func)(); } If works when used with…
Meena Alfons
  • 1,230
  • 2
  • 13
  • 30
27
votes
1 answer

Is it correct to return null shared_ptr?

For example, there is a function that finds an object and returns shared_ptr if object is found, and must indicate somehow that no object was found. std::vector Storage::objects; std::shared_ptr Storage::findObject() { if…
John Lock
  • 623
  • 1
  • 7
  • 18
27
votes
5 answers

Why can't a pointer be automatically converted into a unique_ptr when returning it?

Consider the following program: #include std::unique_ptr get_it() { auto p = new int; return p; } int main() { auto up ( get_it() ); return 0; } This fails to compile with the following error: a.cpp:5:9: error: could…
einpoklum
  • 118,144
  • 57
  • 340
  • 684
27
votes
3 answers

What happens when using make_shared

I'm interested if these two lines of code are the same: shared_ptr sp(new int(1)); // double allocation? shared_ptr sp(make_shared(1)); // just one allocation? If this is true could someone please explain why is it only one…
Tracer
  • 2,544
  • 2
  • 23
  • 58
26
votes
4 answers

Propagate constness to data pointed by member variables

It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct: class SomeClass { …
Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
26
votes
3 answers

Why std::make_unique instead of std::unique_ptr::make?

Why did C++ adopt free functions for: std::make_unique(...); std::make_shared(...); instead of using static member functions: std::unique_ptr::make(...); // static std::shared_ptr::make(...); // static ?
vladon
  • 8,158
  • 2
  • 47
  • 91