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

Is there a way to pass std::make_unique with different classes specified into a function

So I've got this exemplary code. There are 4 bank account-like classes in total used here with Account being an Abstract base class. CheckingAccount and SavingsAccount are derived from the Account abstract class and the TrustAccount is derived from…
1
vote
7 answers

Help me make this code exception-safe

So I have this library code, see... class Thing { public: class Obj { public: static const int len = 16; explicit Obj(char *str) { strncpy(str_, str, len); } virtual void…
ceo
  • 1,138
  • 1
  • 8
  • 16
1
vote
0 answers

Do smart pointers delete memory defined by new

In the following code example, does the destructor of the shared pointer delete the object that's been destructed defined by new? auto object = std::shared_ptr(new Foo()); I found this in some legacy code and I'm wondering if this causes…
marijnr
  • 121
  • 3
1
vote
1 answer

Derive from shared_ptr

I have a strange compilation problem that I can't understand. //I know, you should never derive from the STL Library template class SharedClass : private shared_ptr { public: template SharedClass(T2&& t2) : …
1
vote
1 answer

invoking "operator T()" in c++ smart pointer implementation

I'm using some smart pointer implementation that contain the following operators : template class my_unique_ptr { public: ... operator T() { return _t; } T *operator &() { return &_t; } private: T…
Irad K
  • 867
  • 6
  • 20
1
vote
1 answer

User-defined conversion cannot specify return type

I am implementing unqiue smart pointers with template and I keep getting the compiler error saying user-define conversion cannot specify the return type. Below is my code for both header and cpp files. The error occurs at line 15 of .h and line 48…
Aqleema Sajid
  • 101
  • 1
  • 1
  • 4
1
vote
1 answer

Using a unique pointer to call a function crashes my program

I made a really simple program to try fusing unique pointers and inheritance together. But, it ends up crashing with exit code 11 and I don't know why. Can Anyone explain the reason for the crash? //Counter Class, Base class class Counter { …
Josee
  • 141
  • 1
  • 2
  • 12
1
vote
3 answers

Is using a shared_ptr to share variables between class and its member objects a good solution?

I did this for share the learning_rate between all my neurons : class neural_network { public: neural_network(float learning_rate = 0.005f) : learning_rate(new float(learning_rate)){}; shared_ptr learning_rate; private: …
Matthieu H
  • 525
  • 8
  • 19
1
vote
1 answer

Storing of std::weak_ptr and using static_pointer_cast

Will the reference count still work if storing std::weak_ptr with static_pointer_cast? Here is a very simplifed example (note that the SmallBox and BigBox classes are almost exactly the same): #define OWNER_SMALLBOX 1 #define OWNER_BIGBOX …
1
vote
2 answers

When should I use smart pointers?

There is a similar, very popular question for C++, but I couldn't find a similar existing question for Rust. So, what are the use cases for Box, Rc, Ref, RefMut (others?) in Rust? The important part of the question (for me personally): when should…
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
1
vote
1 answer

How to get integral type from a template type array

Im trying to write a scoped pointer class which calls delete once it is destroyed. I realized that i would need to check whether my pointer is pointing to an array or not, so i could call the right delete. Taking inspiration from std::unique_ptr i…
Denomycor
  • 157
  • 6
1
vote
2 answers

c++: Loki StrongPtr looks unsafe to me, is that so?

I am currently looking at the most popular smart Ptr implementations such as boost shared and weak pointers aswell as loki Smart and Strong pointer since I want to implement my own and from what I understand Loki Strong pointer looks unsafe to me…
moka
  • 4,353
  • 2
  • 37
  • 63
1
vote
2 answers

C++ primer 5 edition: shared_ptr initialized from uniqe_ptr?

On C++ primer 5 edition. Chapter 12. Dynamic memory: It is written: shared_ptr p(u); P assumes ownership from the uniqe_ptr u; makes u null. shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointer q points. q must be…
Itachi Uchiwa
  • 3,044
  • 12
  • 26
1
vote
1 answer

Is using shared_ptr after reset undefined behaviour?

I have this test program: #include #include class A { public: A() { std::cout<<"A Constructor\n"; } ~A(){ std::cout<<"A Destructor\n"; } void show() { …
Zoso
  • 3,273
  • 1
  • 16
  • 27
1
vote
1 answer

Null dangling pointers c++

I have a pointer to an abstract class object ptr1. I need to create another pointer with the same adress ptr2 so that when you free and zero the ptr1 pointer, the ptr2 also becomes zero. SomeObject* ptr1 = new SomeObject(); SomeObject* ptr2 =…
Egor
  • 107
  • 1
  • 8