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
26
votes
8 answers

What's the best signature for clone() in C++?

As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared: class Base { virtual Base* clone() const = 0; }; class Derived : public Base { …
JohnMcG
  • 8,709
  • 6
  • 42
  • 49
26
votes
6 answers

Why shouldn't you use references to smart pointers?

I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up? Thanks for…
Superpolock
  • 3,515
  • 7
  • 30
  • 24
26
votes
1 answer

make_shared and emplace functions

I was trying to find some easy way to emplace elements in a std::vector> but couldn't come with anything. std::shared_ptr takes pointers as parameters, so I can still write this: std::vector>…
Morwenn
  • 21,684
  • 12
  • 93
  • 152
26
votes
6 answers

What is boost's shared_ptr(shared_ptr const & r, T * p) used for?

boost::shared_ptr has an unusual constructor template shared_ptr(shared_ptr const & r, T * p); and I am a little puzzled as to what this would be useful for. Basically it shares ownership with r, but .get() will return p. not…
Evan Teran
  • 87,561
  • 32
  • 179
  • 238
25
votes
2 answers

What does std::make_unique_for_overwrite() do vis-a-vis std::make_unique()?

It appears that in C++20, we're getting some additional utility functions for smart pointers, including: template unique_ptr make_unique_for_overwrite(); template unique_ptr make_unique_for_overwrite(size_t n); and the same…
einpoklum
  • 118,144
  • 57
  • 340
  • 684
25
votes
1 answer

How to make_shared a derived class?

I want to use the make_shared function with a derived class, like below class Base { public: typedef std::shared_ptr Ptr; }; class Derived : public Base {}; Base::Ptr myPtr = std::make_shared(/* Derived() */ ); How can I tell…
Sam
  • 19,708
  • 4
  • 59
  • 82
24
votes
2 answers

Is there an operation for Rc or Arc which clones the underlying value and returns it to the caller?

I'm looking for something roughly like this take, but atomic: impl for Arc { fn take(mut self) -> T { Arc::make_mut(&mut self); Arc::try_unwrap(self).unwrap() } } In other words, I want Arc::make_mut which…
Araz Abishov
  • 1,661
  • 3
  • 15
  • 26
24
votes
4 answers

unique_ptr heap and stack allocation

Raw pointers can point to objects allocated on the stack or on the heap. Heap allocation example: // heap allocation int* rawPtr = new int(100); std::cout << *rawPtr << std::endl; // 100 Stack allocation example: int i = 100; int* rawPtr =…
24
votes
2 answers

Is there a recommended way to test if a smart pointer is null?

I'm trying to check if a std::shared_ptr is null. Is there a difference between doing std::shared_ptr p; if (!p) { // method 1 } if (p == nullptr) { // method 2 }
Sidd
  • 1,168
  • 2
  • 10
  • 27
24
votes
1 answer

Should I delete the move constructor and the move assignment of a smart pointer?

I'm implementing a simple smart pointer, which basically keeps track of the number of references to a pointer that it handles. I know I could implement move semantics, but I don't think it makes sense as copying a smart pointer is very cheap.…
blazs
  • 4,705
  • 24
  • 38
24
votes
10 answers

pros and cons of smart pointers

I came to know that smart pointer is used for resource management and supports RAII. But what are the corner cases in which smart pointer doesn't seem smart and things to be kept in mind while using it ?
Ashish
  • 8,441
  • 12
  • 55
  • 92
23
votes
4 answers

Compiler doesn't fail when pushing back a std::unique_ptr into a std::vector

An unique_ptr cannot be pushed back into a std::vector since it is non-copyable, unless std::move is used. However, let F be a function that returns a unique_ptr, then the operation std::vector::push_back(F()) is allowed. There is an example…
Dan
  • 2,452
  • 20
  • 45
23
votes
2 answers

Is it OK to make a placement new on memory managed by a smart pointer?

Context For test purpose, I need to construct an object on non-zero memory. This could be done with: { struct Type { /* IRL not empty */}; std::array non_zero_memory; non_zero_memory.fill(0xC5); auto…
YSC
  • 38,212
  • 9
  • 96
  • 149
23
votes
2 answers

Factories: how to pass temporary smart pointers to functions. C++

I have a class Foo class Foo; a factory returning a pointer to it: std::unique_ptr createFoo(); and, since I have been told by Herb that a plain function with no special claim on the lifetime of Foo should take plain naked pointers: void…
jimifiki
  • 5,377
  • 2
  • 34
  • 60
23
votes
2 answers

Shared void pointers. Why does this work?

To solve a very peculiar problem in my application I need a shared-pointer to allocated data, but to the outside world, the underlying data type should remain hidden. I could solve this by making some kind of Root class of which all my other classes…
Patrick
  • 23,217
  • 12
  • 67
  • 130