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

How to convert from std::shared_ptr to std::unique_ptr?

So i'm trying to build a template class for binary trees. I have a special way that i want to use to initialize the tree (which you can see in main()). The constructor works with shared_ptr just fine, but i want to move it to more lightweight…
1
vote
4 answers

What are the benefits of using smart pointers over raw pointers for pointer class members here?

The difference between smart pointers and raw pointers has been discussed before (e.g. When should I use raw pointers over smart pointers?), but I can't quite get the answer to this question from the material I have been reading the last day or so.…
user_15
  • 151
  • 9
1
vote
2 answers

What are the pros and cons of receiving a variable as a reference with std::shared_ptr?

I just wondering if the following way of delivering a pointer variable, created inside of the func1, to the caller (func2) is a correct way of doing this. If this is correct, will it release the memory when func2 is returned? If it is a bad idea,…
Chanoh Park
  • 254
  • 2
  • 16
1
vote
2 answers

Keep track of smart pointer in vector

std::vector> v; v.push_back(std::make_unique(1)); unique_ptr& rp0 = v[0]; cout << "rp1="<(2)); cout << "rp1="<
1
vote
2 answers

Templated unique pointer

I'm quite new to C++. I have a class called Main_Alg which runs the (generic) main algorithm. I have different classes with the base class Calc_Type and two derived classes say class A and class B. When Main_Alg is created run will run the generic…
Aylin
  • 21
  • 3
1
vote
1 answer

How to use assert to check whether a weak_ptr is nullptr

The use of assert for checking whether a shared_ptr is not nullPtr is explained in c++ how to assert that all std::shared_ptr in a vector are referring to something but I don't find a decent way to check the same for a weak_ptr. I try to avoid…
JNo
  • 89
  • 12
1
vote
1 answer

Dynamically point to existing or create new object

I have a function, that uses information stored in a struct A. This function is called very often and most of the time it can just rely on the information stored in A. Under some (rare) conditions, one of the objects of A cannot be used. A new…
mathse
  • 13
  • 2
1
vote
2 answers

How to avoid dangling pointer with shared_ptr?

I have a class whose object pointers will be added as a key/data in multiple std::map/std::unordered_map/hash(internally implemented). In order to automate deletion of the object I am using shared_ptr. I have designed my class using shared_ptr only…
nav_jan
  • 2,473
  • 4
  • 24
  • 42
1
vote
3 answers

smart pointers in windows programming

Excluding STL, I only found CComPtr in C++ windows programming. Is there any other types of smart pointers in windows SDK? Thanks.
jiangok
  • 2,622
  • 3
  • 21
  • 26
1
vote
1 answer

Is there a way to Data Watch the Uses of a shared_ptr in visual studio?

Something is holding onto a shared_ptr. I'm wondering if there is a way I can set a Data Watch Breakpoint on the uses of said shared_ptr so I can see the uses increment and decrement. The codebase I'm working in is very large and since we use QT…
1
vote
1 answer

Changing pointed to variable of unique_ptr

I don't think I've understood the concept of smart pointers correctly. Have a look at this MWE: // Example program #include #include #include struct P{ float x, y; P() : x(0.f), y(0.f){} P(float x, float y)…
infinitezero
  • 1,610
  • 3
  • 14
  • 29
1
vote
2 answers

Why is using a reference or unique pointer member of a class a bad thing?

In the book "C++ Coding Standards. 101 Rules, Guidelines, and Best Practices" by Herb Sutter and Andrei Alexandrescu in Rule 52, the final quote is: "In rare cases, classes that have members of strange types (e.g., references, std::auto_ptrs)…
Roman2452809
  • 378
  • 1
  • 2
  • 17
1
vote
1 answer

If I want to transfer a resource, which kind of parameter type should I choose? weak_ptr? or shared_ptr

There is a resource: "aaa", who's type is "AAA". "aaa" is managed by shared_ptr, and we can get it's weak_ptr by function: std::weak_ptr get_aaa_weakPtr(); Now, the client_code want to visit "aaa", and transfer "aaa" to it's child_functions.…
1
vote
2 answers

Pass C++ vector of unique_ptr without passing ownership

I have a class Outer which contains an Inner member and owns a vector of unique_ptr elements: using Elements = std::vector>; class Outer { void call() { _inner.aMethod(_vec); } Inner _inner; …
user997112
  • 29,025
  • 43
  • 182
  • 361
1
vote
1 answer

C++ Factory Pattern with Smart Pointers - can't get past "use of deleted function" error

I'm attempting to make a small C++ Factory Pattern example with smart pointers. Here is what I have so far: // FactorySmart.cpp #include #include #include enum AnimalSpecies { dog, cat }; class Animal { public: …
cdahms
  • 3,402
  • 10
  • 49
  • 75