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

BST with std::unique_ptr: What's difference in using rvalue reference in parameters?

For practice, I'm playing with a binary search tree and a red-black tree with smart pointers. The Node is as follows: template struct BSTNode { T key; std::unique_ptr> left; std::unique_ptr> right; …
frozenca
  • 839
  • 4
  • 14
1
vote
0 answers

Using enable_shared_from_this with smart pointers

Recently, I've tried to exercise Mediator pattern, but my program throws two exceptions. One tells me that there's some problem with empty value, and another one says that there's some problem with "this". What am I doing wrong here? I've…
Thorvas
  • 45
  • 10
1
vote
0 answers

'Base class' : undeclared identifier (Polymorphism)

I'm working on a project in which I'm implementing an interface using SFML. So... I've created one base class SortingAlgorithms, the subclasses that will inherit from the base class and the Interface class which contains the interface…
Daniel
  • 335
  • 1
  • 11
1
vote
1 answer

Implementing copy c'tor with shared pointer?

Since my last question caused a lot of confusion I'm completely going to rewrite it with more info. I have an abstract class Character which is being inherited by Soldier and Medic I wrote another class called Game to manage a game board similar to…
user13756099
1
vote
1 answer

What are situations when a shared smart pointer is needed and unique can't be used?

Seems like maybe shared pointers could be useful across threads when both pointers are accessing same object. But otherwise I can't think of a single time when I would need a shared pointer and a unique pointer wouldn't do the trick. Can you?
mczarnek
  • 1,305
  • 2
  • 11
  • 24
1
vote
2 answers

Can't "std::shared_from_this" be inherited by its derived classes?

Can't std::shared_from_this be inherited by its derived classes? Why doesn't this code snippet compile(check http://cpp.sh/7llcr)? I have read the documentation(https://en.cppreference.com/w/cpp/memory/enable_shared_from_this) carefully, but still…
John
  • 2,963
  • 11
  • 33
1
vote
0 answers

What is the difference between std::vector::emplace_back(new T(args)) and std::vector::emplace_back(std::make_unique(args)) In Assembly?

I ask knowing the difference between these two implementations : std::vector> characters; characters.emplace_back(new Character("Character", 100)); And std::vector> characters; …
rekkalmd
  • 171
  • 1
  • 12
1
vote
1 answer

How to generalize this C++ wrapper around a C 'class'?

I am writing a C++ wrapper around a C library. Here is an example of my strategy. // header file class LibrdfUri { // wrapper around librdf.h librdf_uri* /* * If the deleter of std::unique_ptr is an empty * class…
CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
1
vote
1 answer

Give container ownership of its children, but have children store a reference to their parent using smart pointers

I would like to have all the children of a Node in a tree to be owned by their parent, and have each child store a reference to its parent. That way, when a parent Node is destroyed, all of its children are automatically destroyed. I also expect…
Carpetfizz
  • 8,707
  • 22
  • 85
  • 146
1
vote
1 answer

Creating a custom allocator for CHeapPtr (for use with Sqlite)

I wanted to create some smart pointers for sqlite3 using CHeapPtr. CHeapPtr uses the CCRTAllocator class by default, so I figured I'd just create some custom allocator classes that inherit from CCRTAllocator but override its Free method, so that…
user13366655
1
vote
1 answer

Questions about unique pointers

unique_ptr& operator=(unique_ptr&& _Right) noexcept { if (this != _STD addressof(_Right)) { reset(_Right.release()); _Mypair._Get_first() = _STD forward<_Dx>(_Right._Mypair._Get_first()); } return *this; } Why does the…
김정연
  • 47
  • 2
1
vote
1 answer

No matching member function call to 'push_back', vector of shared pointers

I have a Container class that is meant to store a vector of shared pointers. Whenever an item is appended to the Container, I want it to assume ownership of that item. In other words, when the Container is deconstructed, all of the elements inside…
Carpetfizz
  • 8,707
  • 22
  • 85
  • 146
1
vote
1 answer

Temporary pointer before releasing?

I've took a look into atlbase.h to see how CComPtr<> is implemented, and stumbled upon Release() function in base class CComPtrBase<> which releases the underlaying object like this: // Release the interface and set to NULL void Release() throw() { …
metablaster
  • 1,958
  • 12
  • 26
1
vote
2 answers

std::shared_ptr in Bison causing member error

I'm trying to make bison more memory efficient by using std::shared_ptr. I do not want to use raw pointers. I'm using a node system as the parse tree so I define YYTYPE as std::shared_ptr. After running it with some simple grammar, I get the…
Tom
  • 1,235
  • 9
  • 22
1
vote
2 answers

Smartpointers do not work well with a generic TObjectlist in Delphi

I am testing smart-pointers in Delphi 10.3 Rio using Spring4D. Here is my test program. I created a generic TObjectList and I want to add simple TObjects to this list using Shared.Make(TTestObj.Create). The problem is that whenever I add an object…