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
34
votes
7 answers

C++ using scoped_ptr as a member variable

Just wanted opinions on a design question. If you have a C++ class than owns other objects, would you use smart pointers to achieve this? class Example { public: // ... private: boost::scoped_ptr data; }; The 'Owned' object can't be…
Ray Hidayat
  • 16,055
  • 4
  • 37
  • 43
34
votes
4 answers

Vector of shared pointers , memory problems after clearing the vector

I realized that after calling vector.clear() which hold shared pointers, the destructors of the object which own by shared_ptr is not being released. Code example can be seen below . Even vector.clear() being called, destructor called after shared…
Kadir Erdem Demir
  • 3,531
  • 3
  • 28
  • 39
34
votes
2 answers

Should I use C++11 emplace_back with pointers containers?

Having a usual Base -> Derived hierarchy, like: class Fruit { ... }; class Pear : Fruit { ... }; class Tomato : Fruit { ... }; std::vector m_fruits; Does it make sense (e.g: is performance better) to use emplace_back instead of…
Zhen
  • 4,171
  • 5
  • 38
  • 57
34
votes
2 answers

unique_ptr lambda custom deleter for array specialization

I recently started porting lots of my existing C++ application code to over to C++11 and now that I am converting to the new smart pointers std::unique_ptr and std::shared_ptr, I have a specific question about custom deleters. I want to add a lambda…
johnco3
  • 2,401
  • 4
  • 35
  • 67
33
votes
9 answers

best practice when returning smart pointers

What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels…
Rolle
  • 2,900
  • 5
  • 36
  • 40
33
votes
3 answers

does make_unique value initializes char array

For example - #include int main(){ const auto bufSize = 1024; auto buffer = std::make_unique(bufSize); } Is the buffer here already filled with '\0' characters or will I have to manually fill it to avoid garbage…
Abhinav Gauniyal
  • 7,034
  • 7
  • 50
  • 93
33
votes
1 answer

Lock-free Reference counting and C++ smart pointers

In general, most widely known implementations of reference-counting smart ptr classes in C++, including the standard std::shared_ptr, use atomic reference counting, but do not provide atomic access to the same smart ptr instance. In other words,…
Siler
  • 8,976
  • 11
  • 64
  • 124
32
votes
7 answers

How does a reference-counting smart pointer's reference counting work?

In other words, how does the implementation keeps track of the count? Is there a map-like object maintained which is accessible by all the shared_ptr instances whose key is the pointer's address and value is the number of references? If I've to…
Srikanth
  • 11,780
  • 23
  • 72
  • 92
32
votes
1 answer

Set shared_ptr with new_pointer that is old_pointer + offset

Here is a smart pointer: std::shared_ptr p(new char[size]) which represents array filled with raw binary file content. After (and only after) the whole array is copied from file to RAM, I can parse it, and during this I retrieve some header…
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
32
votes
5 answers

What is diffrence between lock() and expired()? weak_ptr C++

Recently I started at C++11. I studied about weak_ptr. There exist two ways of getting raw pointer. lock() function shared_ptr spFoo = wpPtr.lock(); if(spFoo) { spFoo->DoSomething(); } expired() function if(!wpPtr.expired()) { …
zeno
  • 351
  • 1
  • 3
  • 7
31
votes
4 answers

How to check memory allocation failures with new operator?

Just recently I switched the language of my project to use C++ from C. With C, I used malloc and after that I check if malloc was successful but with C++, I use 'new' to allocate memory and I would like to know how you would normally check the…
istudy0
  • 1,313
  • 5
  • 14
  • 22
31
votes
1 answer

How to avoid memory leak with shared_ptr?

Consider the following code. using boost::shared_ptr; struct B; struct A{ ~A() { std::cout << "~A" << std::endl; } shared_ptr b; }; struct B { ~B() { std::cout << "~B" << std::endl; } shared_ptr a; }; int main() { …
Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
31
votes
9 answers

C++ - Run a function before initializing a class member

I have 2 resource managing classes DeviceContext and OpenGLContext both are members of class DisplayOpenGL. The resource lifetimes are tied to DisplayOpenGL. Initialization looks like this (pseudo code): DeviceContext m_device =…
30
votes
4 answers

Create a boost::shared_ptr to an existing variable

I have an existing variable, e.g. int a = 3; How can I now create a boost::shared_ptr to a? For example: boost::shared_ptr< int > a_ptr = &a; // this doesn't work
Bill Cheatham
  • 11,396
  • 17
  • 69
  • 104
30
votes
10 answers

Is it possible to use a C++ smart pointers together with C's malloc?

Some of my code still uses malloc instead of new. The reason is because I am afraid to use new because it throws exception, rather than returning NULL, which I can easily check for. Wrapping every call to new in a try{}catch(){} also doesn't look…
bodacydo
  • 75,521
  • 93
  • 229
  • 319