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

shared_ptr strange behaviour

This the first question I'm doing. I've searched a lot but couldn't find the answer. I'm learning the use of smart pointers on c++14 and the compiler is g++ 5.4. I want to know why is the variable "t" still prints a value when the reassignment of…
1
vote
1 answer

Problem with reference initialization in constructor

Class pseudo definition: Base Virtual Class A: class A { public: virtual ~A(); virtual void doSomething() const = 0; }; Class B Inheriting from A: class B : public A { public: void doSomething() {} const; } Base Virtual Class C: class…
Advent
  • 140
  • 15
1
vote
2 answers

Using smart pointers in Doubly Linked Lists

Here are the things I know about smart pointers shared_ptr is a smart pointer such that multiple shared_ptr can point to an object in the heap. Even if one of the shared_ptr is deleted the object in the heap will not be destroyed as long as it's…
Gauranga Das
  • 19
  • 1
  • 3
1
vote
1 answer

Read Access Violation using Smart Pointers

I am trying to use push_back as part of a member function in class StrBlobm to add elements to a vector in a shared pointer also contained in StrBlobm, but I keep getting this error: Exception thrown: read access…
Mild Max
  • 37
  • 1
  • 8
1
vote
2 answers

Creating a smart pointer in a struct?

I'm modeling a Node in a Binary Tree using a struct. In the struct, I'm trying to have a pointer to the left and right child. The problem is, I keep running into a stack overflow due to the way I'm creating the struct. It seems the way I've been…
Mr.Mips
  • 379
  • 2
  • 18
1
vote
2 answers

C++ access member of templated derived class without typecast

Is it possible to acces a member of a derived class using a pointer to the base class? // Example program #include #include #include #include class A { public: std::string x = "this is the wrong x\n"; …
po.pe
  • 1,047
  • 1
  • 12
  • 27
1
vote
2 answers

C++ smart pointers for objects containing raw pointers

I have a class having an element which contains a raw pointer of another object as following. Note that the example I simplified from my actual work may probably work, but I am trying to get conceptual mistake if I am doing here, because in the…
iesiyok
  • 79
  • 2
  • 10
1
vote
1 answer

Copy&Swap efficiency for shared pointers

This can be seen as a follow up to e.g. Why shared pointer assignment does 'swap'?. The question is about the Copy&Swap idiom used e.g. in boost. I do understand that the benefit of Copy&Swap is to reuse existing code which avoids duplication and…
Flamefire
  • 5,313
  • 3
  • 35
  • 70
1
vote
1 answer

How to return a list of unique_ptr in c++?

Here is a code snippet which i want to get a list of unique_ptr from a function. Although i have added Copy/move Constructor to this struct,the vs compiler still has reported a c2280 error(attempting to reference a deleted function) .Does anybody…
Y.Lex
  • 241
  • 1
  • 7
1
vote
1 answer

Why am I losing these constructed objects with smart pointers, but not new?

I think I'm misunderstanding something about smart pointers. Take a look at the following example. When I use new/*, I get exactly what I expect, but when I use std::shared_ptr, I get a null pointer error. Isn't the smart pointer implementation…
Carbon
  • 3,828
  • 3
  • 24
  • 51
1
vote
3 answers

Plain reference instead of weak_ptr to break circular dependency

Taking a look at std::weak_ptr I have seen in a couple of places that it can be used to break memory leaks due to circular dependencies using std::shared_ptr. See for example these two accepted answers: [1], [2]. Taking the last referenced answer,…
user2891462
  • 3,033
  • 2
  • 32
  • 60
1
vote
2 answers

deep copy of objects containing unordered_map of unique_ptr

I have the following situation: I need to create a deep (!) copy of a variable from type A. This variable contains a vector of type B. Class B is not copyable, because it contains a std::unordered_map whos value is a unique_ptr (which is not…
user7431005
  • 3,899
  • 4
  • 22
  • 49
1
vote
1 answer

C++: How to initialize following std::shared_ptr constructor array

I have a abstract class named Base from which I derived a class(Derived) as follows: #include #include #include class Base { public: virtual void printClass()const = 0; virtual ~Base(){} }; class Derived:…
JeJo
  • 30,635
  • 6
  • 49
  • 88
1
vote
2 answers

remove smart_ptr from inside function

Is there any way to destroy a std::shared_ptr from within a function? In the following example if I set the sptr to nullptr in main() it "destroys" the object so calling it's Print() fails. However, doing so inside the Delete() function doesn't do…
user441521
  • 6,942
  • 23
  • 88
  • 160
1
vote
1 answer

Issue with polymorphism with smart pointers and vectors c++

I am currently trying to learn c++ and I am having an issue when trying to create a vector which iterates through several different objects whom all inherit from the same base class with smart pointers. I parse a file and create the objects and…
user9237024
1 2 3
99
100