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
47
votes
5 answers

Passing unique_ptr to functions

I'm trying to "modernize" some existing code. I have a class which currently has a member variable "Device* device_". It uses new to create an instance in some initialization code and has a "delete device_" in the destructory. Member functions…
jcoder
  • 29,554
  • 19
  • 87
  • 130
47
votes
4 answers

How to perform a dynamic_cast with a unique_ptr?

I have a class hierarchy as follows: class BaseSession : public boost::enable_shared_from_this class DerivedSessionA : public BaseSession class DerivedSessionB : public BaseSession Within the derived class functions, I regularly call…
Sharath
  • 1,627
  • 2
  • 18
  • 34
46
votes
2 answers

How to initialize std::unique_ptr in constructor?

A.hpp: class A { private: std::unique_ptr file; public: A(std::string filename); }; A.cpp: A::A(std::string filename) { this->file(new std::ifstream(filename.c_str())); } The error that I get is thrown: A.cpp:7:43:…
user1529891
45
votes
1 answer

What is the difference between Rc> and RefCell>?

The Rust documentation covers Rc> pretty extensively but doesn't go into RefCell>, which I am now encountering. Do these effectively give the same result? Is there an important difference between them?
Gman man
  • 475
  • 1
  • 4
  • 8
45
votes
2 answers

Why is std::rc::Rc<> not Copy?

Can someone explain to me why Rc<> is not Copy? I'm writing code that uses a lot of shared pointers, and having to type .clone() all the time is getting on my nerves. It seems to me that Rc<> should just consist of a pointer, which is a fixed size,…
rix0rrr
  • 9,856
  • 5
  • 45
  • 48
45
votes
4 answers

What is the best smart pointer return type for a factory function?

With respect to smart pointers and new C++11/14 features, I am wondering what the best-practice return values and function parameter types would be for classes that have these facilities: A factory function (outside of the class) that creates…
Malvineous
  • 25,144
  • 16
  • 116
  • 151
43
votes
6 answers

How to assign the address of an existing object to a smart pointer?

#include class bar{}; void foo(bar &object){ std::unique_ptr pointer = &object; } I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator…
Tomasz Kasperczyk
  • 1,991
  • 3
  • 22
  • 43
41
votes
5 answers

Is the Rule of 5 (for constructors and destructors) outdated?

The rule of 5 states that if a class has a user-declared destructor, copy constructor, copy assignment constructor, move constructor, or move assignment constructor, then it must have the other 4. But today it dawned on me: when do you ever need a…
SomeProgrammer
  • 1,134
  • 1
  • 6
  • 12
40
votes
4 answers

How to enable Rust Ownership paradigm in C++

The system programming language Rust uses the ownership paradigm to ensure at compile time with zero cost for the runtime when a resource has to be freed. In C++ we commonly use smart pointers to achieve the same goal of hiding the complexity of…
Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
39
votes
1 answer

Why does unique_ptr instantiation compile to larger binary than raw pointer?

I was always under the impression that a std::unique_ptr had no overhead compared to using a raw pointer. However, compiling the following code #include void raw_pointer() { int* p = new int[100]; delete[] p; } void smart_pointer() { …
Alessandro Power
  • 2,395
  • 2
  • 19
  • 39
39
votes
1 answer

intrusive_ptr in c++11

Does C++11 have something equivalent to boost::intrusive_ptr? My problem is that I have a C-style interface over my C++ code. Both sides of the interface can use C++, but exposing the C interface is required for compatibility reasons. I cannot use…
Aarkan
  • 3,811
  • 6
  • 40
  • 54
38
votes
5 answers

shared_ptr vs scoped_ptr

scoped_ptr is not copy able and is being deleted out of the scope. So it is kind of restricted shared_ptr. So seems besides the cases when you really need to restrict the copy operation shared_ptr is better to use. Because sometimes you don’t know…
Narek
  • 38,779
  • 79
  • 233
  • 389
37
votes
4 answers

C++11 Smart Pointer Semantics

I've been working with pointers for a few years now, but I only very recently decided to transition over to C++11's smart pointers (namely unique, shared, and weak). I've done a fair bit of research on them and these are the conclusions that I've…
SamuelMS
  • 1,116
  • 1
  • 11
  • 22
35
votes
4 answers

Return Type Covariance with Smart Pointers

In C++ we can do this: struct Base { virtual Base* Clone() const { ... } virtual ~Base(){} }; struct Derived : Base { virtual Derived* Clone() const {...} //overrides Base::Clone }; However, the following won't do the same trick: struct…
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
34
votes
5 answers

How do smart pointers choose between delete and delete[]?

Consider: delete new std :: string [2]; delete [] new std :: string; Everyone knows the first is an error. If the second wasn't an error, we wouldn't need two distinct operators. Now consider: std :: unique_ptr x (new int [2]); std ::…
spraff
  • 32,570
  • 22
  • 121
  • 229