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

Inserting a Smart Pointer in a Unordered Map calls destructor

I'm making an engine and to handle materials stuff I have a static renderer class storing a static std::unordered_map> m_Materials; (a material and its ID), being Ref the a shared pointer using the next methods: template
LuchoSuaya
  • 77
  • 10
1
vote
1 answer

A weak smart pointer that calls a handler when object being deleted?

I find surprising that people that use std::weak_ptr do not find it useful to bind onDelete handlers to their references. I've been looking around in boost but I haven't found anything like this. Am I missing something? Is a "bad smell" to rely on…
lurscher
  • 25,930
  • 29
  • 122
  • 185
1
vote
1 answer

Crash when method of class is executing but smart pointer deleted the object

I faced a problem with C++ memory management and smart pointers. I have a code to demonstrate you the problem: #include class Closeable { public: virtual void Close() = 0; }; class DisconnectionHandler { public: virtual void…
zenno2
  • 425
  • 2
  • 7
1
vote
1 answer

Smart pointer with local buffer optimization

This is example of smart pointer with type erased deleter and local buffer optimization enabled. It is from the book…
Ashot
  • 10,807
  • 14
  • 66
  • 117
1
vote
1 answer

seg fault static class member pointer used with dynamic allocation

I am running into seg fault as shown cluster_init: /usr/include/boost/smart_ptr/shared_ptr.hpp:728: typename boost::detail::sp_dereference::type boost::shared_ptr::operator*() const [with T = pcl::PointCloud; typename…
Iberico
  • 162
  • 2
  • 15
1
vote
0 answers

Ambiguity while referencing privately inherited method from of base class

I have a base class and child class. I want shared_from_this to return shared_ptr to the object in which it is invoked. So if shared_from_this() is called on child it should return a shared_ptr to child and same way for base. Below is my sample…
chandola
  • 126
  • 1
  • 10
1
vote
1 answer

Rust Box and move

I have the following code: use std::{borrow::BorrowMut, mem}; struct Node { ele: i32, next: List, } enum List { Empty, More(Box), } pub struct LinkedList { head: List, } impl LinkedList { pub fn new() -> Self { …
jctaoo
  • 89
  • 3
  • 9
1
vote
2 answers

C++ Initializer list when dependencies do not have copy ctor or assignment operator

Approach 1 I have some type Foo which internally contains a std::mutex. class Foo { std::mutex m_; }; I wrote another class Bar. Bar has Foo as a member and a constructor, like this (note - this code doesn't compile): class Bar { Bar(Foo foo) :…
Beebunny
  • 4,190
  • 4
  • 24
  • 37
1
vote
1 answer

shared_ptr and unique_ptr constructor

When I use smart pointers, I always need to construct it with the factory functions, e.g. std::make_shared and std::make_unique, I don't use the constructor which takes a pointer because I try to avoid any usage/appearances of new. But my…
fluter
  • 13,238
  • 8
  • 62
  • 100
1
vote
2 answers

unique_ptr is calling destructor twice

I have a block of code where I am using unique_ptr. class Abc { public: std::string msg; Abc(std::string m) { msg = m; std::cout << "Constructor: " << msg << std::endl; } ~Abc() { std::cout << "Destructor: "…
Sajib
  • 404
  • 3
  • 15
1
vote
1 answer

Tree Traversals with smart pointers

I have implemented a simple binary tree class in C++. have using smart pointers objects to hold the pointers to each node (shared for children and weak for parent). I was trying to implement a nested class for custom iterator (in-order, pre-order…
Kfir Ettinger
  • 584
  • 4
  • 13
1
vote
3 answers

C++ unique_ptr; Why this sample codes get compile error?? error codes are so long that I can't specify it

I'm studying about smart pointer now, and I just built the sample codes in the book. But when I use unique_ptr like this code below, it makes compile error. The error codes are so long that they are almost cut, so I can't write down them all. I…
1
vote
1 answer

Is it valid to move and use unique pointer in single statement?

I am getting segmentation fault on below line of my code with stacktrace as stated below. self is a unique_ptr here. self->socket.async_send_to(self->frame->get_asio_buffer(), self->client_endpoint, …
chandola
  • 126
  • 1
  • 10
1
vote
1 answer

Error using `make_shared( std::size_t N )`

I am trying to implement a fixed size multi-dimensional array whose size is determined at runtime. with the (2) overload of make_shared (template shared_ptr make_shared(std::size_t N) // T is U[]). However, I am facing compilation errors…
SuibianP
  • 99
  • 1
  • 11
1
vote
1 answer

Question about keeping a reference to a unique_ptr in another class

Recently, I decided that it was time that I should dig into smart pointers. I read about the different kinds (unique, shared, weak), but I'm not sure about one thing. Let say that I have a class Player and a GameMap class. The content of those…
Coulis
  • 196
  • 1
  • 13