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

Instead of creating smart pointers, Why could we not have modified C++ compilers to better catch pointer issues at compile time?

If we could design smart pointers to know when to destroy/delete heap memory based on the scope. Why couldn't we have just engineered the compiler to have flagged when heap memory was going out of scope without being deleted? Why was it more…
Seth Van
  • 25
  • 7
1
vote
1 answer

How to use std::min_element on map with unique pointer values? (C++)

I have a map with unique pointer values, and want to get a reference to the pair with the smallest value. I'm using the code below to do this, but am getting an error in the line where I call std::min_element. The error message is: no matching…
user6429576
1
vote
1 answer

Move assignment operator is not moving my shared_ptr

I'm having some trouble with my move assignment operator, and maybe I'm just misunderstanding what's going on. My SignalHolder object below is meant to hold a shared pointer to a Signal object and call its detach() method as soon as the…
kitfox
  • 4,534
  • 3
  • 17
  • 24
1
vote
1 answer

Constructing shared_ptr from unique_ptr with and without move?

I see in the highly-upvoted answer here (https://stackoverflow.com/a/37885232/3754760) there are two ways to convert a unique_ptr to a shared_ptr, namely by creating the unique_ptr first and then move-ing it to the shared_ptr, as well as assigning…
jj172
  • 751
  • 2
  • 9
  • 35
1
vote
1 answer

std::unique_ptr::reset overloads questions

From the https://en.cppreference.com/w/cpp/memory/unique_ptr/reset members of the primary template, unique_ptr void reset( pointer ptr = pointer() ) noexcept; (1) template< class U > void reset( U ) noexcept; (2) void…
Johy
  • 263
  • 2
  • 10
1
vote
1 answer

gtkmm widgets - use smartpointers or pointers?

I am trying to learn how to use gtkmm having got a basic grasp of C++ (I like a challenge!). I have been working my way through the tutorials (as well as other reading). I am trying to use the approach of using glade to design the UI and then…
MartynW
  • 641
  • 2
  • 7
  • 23
1
vote
1 answer

Strong Pointer causing a heap corruption on application closing when std::vector is present

I am getting a strange heap corruption error during the application close where if a "std::vector" is present in my code, AND I am deleted my "ref_count" variable. If I don't have an std::vector, there is no crash. If there is a std::vector and I…
chadb
  • 1,138
  • 3
  • 13
  • 36
1
vote
0 answers

C++ store objects in vectors with a stable address

I want to have a place to store my objects. A vector is a good choice for this but I also want to pass a pointer to those elements to other objects. The problem is that when I push_back, the vector might invalidate all the references... Should I use…
Jojolatino
  • 696
  • 5
  • 11
1
vote
2 answers

Different address of std::unique_ptr::get and operator&

Using pointers in the example below gave me a confusion so I probably misunderstand something. I will try to show my way of understanding and some pseudo-simple example. Creating std::unique_ptr variable of name my_int ensures that it can not be…
Kuba
  • 11
  • 2
1
vote
1 answer

CRTP with smart pointers

I am experimenting with the concept of CRTP and how it can be used to approximate mixins in C++. I've developed the following code to illustrate the idea, but came across a problem when the vector shapeVec tries to delete the smart pointers, it…
1
vote
3 answers

Unique Pointer Creating copy of the object but i want to avoid the copy

I read somewhere if you want to return a local variable via reference do it via smart pointers and the motivation behind this code is exacttly the same i want to return a Test class variable without it copy being created or in other words Return a…
Umar Farooq
  • 418
  • 2
  • 14
1
vote
3 answers

Passing std::shared_ptr to thread and going out of scope immediately

I'm creating a small C++ server which is supposed to handle requests in an infinite loop like. void Server::start_accept_loop(int server, SSL_CTX* ctx){ sockaddr_in incoming_addr; socklen_t len = sizeof(incoming_addr); int client_sock; …
user123
  • 2,510
  • 2
  • 6
  • 20
1
vote
0 answers

Why std::vector of pointers avoid deconstruction bugs?

In one of my project I managed to fix a bug switching from a std::vector of objects to a std::vector of pointers to the object. Using the debugger I found that the error occurred when I was calling the std::vector::clear that it is…
apelle
  • 144
  • 1
  • 9
1
vote
1 answer

How to create a custom shared_ptr?

Say I have a library SXY which gives me a picture from a file: Picture * pic; pic=get_picture("directory/file") And I share it over multiple functions. But I want to call picture_close(pic) to dellocate it only when I am done and all these…
Zeor137
  • 165
  • 1
  • 2
  • 11
1
vote
1 answer

Is a unique_ptr equipped with a function pointer as custom deleter the same size as a shared_ptr?

I know that std::unique_ptr and std::shared_ptr are different classes that address different needs, and therefore asking which one is better is mostly an ill-posed question. However, as regards their content and performance, without considering the…
Enlico
  • 23,259
  • 6
  • 48
  • 102