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
1
vote
2 answers

How to safely use unique_ptr with functions which can return NULL?

I've noticed that this compiles: #include #include using namespace std; int main() { unique_ptra(nullptr); if(!a) cout<<"NULLPTR"; } However, this doesn't: #include #include using namespace…
Vishal Sharma
  • 1,670
  • 20
  • 55
1
vote
1 answer

C++: char* vs char(*)[]

I'm new with C++ and came to this problem, here is my code: shared_ptrvar(new char[20]); char *varptr = *(var.get()); So I'm creating smart pointer of char array. The problem that I'm having is that during compilation it gives me error…
Ojs
  • 924
  • 1
  • 12
  • 26
1
vote
1 answer

Create object using parameters pack in template

I'd like to create template function that would create object basing on template typename and parameters pack. I created a function that is supposed to create object based on typename from template, and I would also like to pass parameters pack to…
1
vote
2 answers

How to correctly use map with smart pointers and custom classes as key and value

I'm trying to make map in which i will hold Teams as key and vector of Employees which are polymorphic as value. Some of the data will be loaded from file in future and the user will be able to add new teams and employees at any time. This is the…
1
vote
1 answer

How to use unique_ptr for iteration?

I have a binary search tree implementation where each node of the tree has this structure. struct node { T data; std::unique_ptr left, right; node(T data): data(data), left(nullptr), right(nullptr) {} }; I have…
bornfree
  • 2,308
  • 1
  • 23
  • 33
1
vote
1 answer

Can std::make_unique take the output of a function as an argument?

Is there a way to use make_unique and pass the output of a function as a parameter? auto loadedSurface1 = std::unique_ptr(IMG_Load(path.c_str())); auto loadedSurface2 = std::make_unique
user250095
  • 13
  • 3
1
vote
3 answers

Reassign a smart pointer in a function without passing ownership?

Background With normal pointers, I can do something like the following void conditional_reassign(MyClass* ptr) { if (my_condition) { delete ptr; ptr = new MyClass(new_param); } } And I can pass in the pointer I want to…
Rufus
  • 5,111
  • 4
  • 28
  • 45
1
vote
1 answer

Why does reassigning a smart pointer to itself cause destruction?

TLDR Why does the line t_ptr = std::unique_ptr(t_ptr.get()); cause the destructor to be called? The line seems to just innocently assign t_ptr back to itself... Further, why am I able to continue calling methods after the supposed…
Rufus
  • 5,111
  • 4
  • 28
  • 45
1
vote
2 answers

Optimize calls to allocator when replacing the content of a shared pointer

Consider this program: #include struct T { T() {} }; void do_something(std::shared_ptr ptr) { // Do something with ptr; might or might not leave // other copies of ptr in other variables of the // program } int main()…
Giovanni Mascellani
  • 1,218
  • 2
  • 11
  • 26
1
vote
0 answers

Invalid free() / delete / delete[] / realloc() with std::shared_ptr

I'm new to using C++ smart pointers. I wanted to use them in one large project I'm working on, but I'm getting the following error: ==21819== Invalid free() / delete / delete[] / realloc() ==21819== at 0x4838E7B: operator delete(void*) (in…
Eenoku
  • 2,741
  • 4
  • 32
  • 64
1
vote
3 answers

Safely contain arbitrary data in a smart pointer

First off: I searched half the web to find an answer with this as a solution that came closest. It is, however, too heavyweight for me though so I am looking a little less complex. Well then, some context: I am building a system which should be able…
Nebula
  • 1,045
  • 2
  • 11
  • 24
1
vote
1 answer

Why sized trait is required for a builder function to generate Rc?

This code works fine (playground): use std::rc::Rc; trait Foo { fn foo(&self); } struct Bar { v: Rc, } impl Bar where T: Foo { fn new(rhs: Rc) -> Bar { Bar{v: rhs} } } struct Zzz { } impl Zzz { fn…
Eric Wu
  • 15
  • 5
1
vote
2 answers

How can I track cases when a pointer from a "new" expression is passed to dynamic_cast?

Recently I found the following while reviewing some old code: auto_ptr pointer = dynamic_cast( new CDerived() ); aside from the fact that this code is meaningless in valid cases (in valid cases class Derived is derived from…
sharptooth
  • 167,383
  • 100
  • 513
  • 979
1
vote
1 answer

Why is the destructor not called for Box::from_raw()?

I am passing a raw pointer to two different closures and converting the raw pointer to a reference using Box::from_raw() and the program is working fine. However, after converting the raw pointer to reference, the destructor should be called…
A-B
  • 487
  • 2
  • 23