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

How can I declare smart pointers in a header file with incomplete forward-declared classes?

I have a header with forward-declared classes that I want to declare some smart pointer members in. However, since the smart pointer template types are technically incomplete at time of declaration, I'm getting compilation errors regarding sizeof…
1
vote
1 answer

Template polymorphism and unique_ptr

I'm currently trying to program a pipeline, which is able to process different kind of data in every pipeline element. Now I want to use unique_ptrs with some kind of template polymorphism and template specialization. struct Start {}; // Dummy…
1
vote
1 answer

What exactly is the ownership when we talk about smart pointers in C++?

While reading about smart pointers, especially in the case of std::shared_ptr & std::weak_ptr, I have often found people using the term "ownership" or "it owns the object". But what exactly is this ownership? It's even more confusing while trying to…
Milan
  • 1,743
  • 2
  • 13
  • 36
1
vote
1 answer

shared_ptr does not destruct the object at the end of the program

I'm trying to implement a Deque using smart pointers. However, I noticed that at the end of the program the Nodes of the Deque are not destructed properly. Here is the code: #include #include class Node { int value; …
Cantaro
  • 77
  • 6
1
vote
1 answer

Building CXX object CMakeFiles error : ProductCategory *result = 0 ; was not declared in the scope (SaleItem has Product Category Pointer as member )

I have a SaleItem class that has a pointer of an another class Product Category as member function, the getter of the SaleItem class that returns the pointer to the ProductCategory is causing the error. The IDE does not give the error straightaway…
rrajanuk
  • 27
  • 8
1
vote
2 answers

How to wrap a list of pointers to abstract class?

I try to wrap a list of smart pointers to abstract class (list> list_) into some classes (Item, Drawer, Box). Then in the main function, I have a map of Box'es and it doesn't work. I found a way around and I can use new but I…
1
vote
1 answer

Create std::shared_ptr using factory function

I have a class Foo which is not instantiated directly but through a static factory method Foo Foo::create_foo(). Now I want to create a std::shared_ptr. Normally I would use auto ptr = std::make_shared(); How can I achieve the same while…
luator
  • 4,769
  • 3
  • 30
  • 51
1
vote
1 answer

Pop method of linked list using unique_ptr

I'm looking at the implementation of a singly linked list using unique_ptr on https://solarianprogrammer.com/2019/02/22/cpp-17-implementing-singly-linked-list-smart-pointers/. My question pertains to the following method: 3 struct List { 4 …
roulette01
  • 1,984
  • 2
  • 13
  • 26
1
vote
2 answers

pointer to const int using smart pointer

I am trying to create a smart pointer (unique_ptr) to a value returned as const int& but my issue can be summed up as easily as: const int value = 5; const int * ptr{nullptr}; ptr = &value; This works, and compile as expected. When trying to the…
Tomas Berger
  • 173
  • 1
  • 3
  • 15
1
vote
1 answer

Why am I getting a crash after calling my constructor? I'm trying to push back a shared_ptr to a vector

I'm quite new to programming (currently learning C++). I'm trying to learn how to use smart pointers. I'm trying to do a challenge from a tutorial in which the goal is to fill in data points to a unique_ptr of a vector that contains shared_ptrs that…
GCW
  • 13
  • 2
1
vote
2 answers

How are smart pointers of a derived class implicitly convertible to the base class?

From cppreference, If T is a derived class of some base B, then std::unique_ptr is implicitly convertible to std::unique_ptr which it obviously must be for polymorphism to work as it does with raw pointers. My question is, if a smart pointer…
crdrisko
  • 454
  • 2
  • 5
  • 14
1
vote
1 answer

Shared_ptr implementation

I have written an implementation of Shared_ptr as part of working through the C++ Primer book. The header file does compile correctly, however I'm receiving several "No matching function" errors when I try to use it with a `Blob' class. I've spent…
1
vote
1 answer

Using smart pointers within multi-threaded application

I have some calculation I need to perform that is dependent on two or more steps as follows: class A { public: double step1() { return 2.5; } }; class B { public: double step2() { return 1.2; } }; class Result { public: …
1
vote
0 answers

Dynamic member data using unique_ptr and returning data

I want to use unique_ptr to dynamically allocate some member array data in my class (please don't comment about vectors or arrays). I understand how to create my arrays but I am wondering about returning them with getter functions. I want my class…
zstreet
  • 126
  • 9
1
vote
1 answer

Red-Black Tree with std::unique_ptr

I'm playing with Red-Black Tree with std::unique_ptr but it doesn't work. My node definition: enum class Color { Red, Black }; template struct Node { T key; Color color; std::unique_ptr> left; …
frozenca
  • 839
  • 4
  • 14