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
0 answers

Crash occurs with observer pattern using smart_ptrs

I am trying to implement observer design pattern using C++ 11 smart pointers. Below is my code. The below program crashes if we try to remove the observer from the subject. //observer class iobserver { public: virtual…
1
vote
0 answers

c++ Moving a temporary object prevents copy elision (fix available)clang(-Wpessimizing-move) error

I am writing cmu 15-445 projects0, when i convert 'unique_ptr' to 'shared_ptr', i got "Moving a temporary object prevents copy elision" error, here is my code. Trie new_trie = Trie(std::shared_ptr(std::move(root_->Clone()))); //…
BaotongJin
  • 11
  • 3
1
vote
1 answer

Does .get() from shared_ptr copy?

Let's see the following code: #include #include using namespace std; class myClass{ public: int a = 15; myClass(int x): a(x){}; ~myClass(){cout << "die die ";}; }; int main() { myClass* c; { …
Ivan
  • 1,352
  • 2
  • 13
  • 31
1
vote
2 answers

How to handle heap allocated fixed length byte buffers?

In C we use char* to point to a block of memory allocated with malloc and keep track of the size in a separate size/length variable. What is the C++ equivalent? From what I've seen so far most people use std::vector. Typically .resize() is called to…
1
vote
1 answer

Creating Multiple Mutexes in Rust for Thread Synchronization

I'm not familiar with Rust. The program I'm trying to write will have the value of n determined at runtime. I want the program to have the following behavior: n threads will be created, each interacting with a user and storing data (these are slave…
1
vote
0 answers

Cannot make std::unique_ptr hold a pointer to std::ifstream

Consider the following piece of code (out of context for the sake of simplicity): std::unique_ptr stream; stream = std::make_unique(path, std::ios::in | std::ios::binary); This code compiles just fine with MSVC and…
Kaiyakha
  • 1,463
  • 1
  • 6
  • 19
1
vote
0 answers

Smart pointers and initialization

int number_of_elements = 5; std::shared_ptr dataholder; dataholder = std::make_shared(number_of_elements); for (int i = 0; i < number_of_elements; i++) dataholder[i] = rand() % 100; // -----> This line for (int i = 0; i <…
koolaid
  • 31
  • 2
1
vote
1 answer

Should I use an std::vector or a std::unique_ptr here?

I have a Mesh class that I want to have ownership over several different "array-like" structures for vertices,indices,vertex_normals,etc. I would like for the Mesh class to be totally independent of the source of these formats, as I have many 3d…
Chris Gnam
  • 311
  • 2
  • 7
1
vote
2 answers

Cannot assign derived raw pointer to base unique_ptr

I have some code that looks something this: class Info { public: virtual bool IsHere() = 0; virtual std::wstring GetStr() = 0; }; class WindowsInfo : public Info { public: virtual std::wstring GetAnotherStr() = 0; bool IsHere()…
conectionist
  • 2,694
  • 6
  • 28
  • 50
1
vote
1 answer

What is the difference between shared_ptr and shared_ptr?

I have a class variable ptr, I want it to point to the first element of my 1D int array. What is the difference between these two statements, and which one should I use? shared_ptr ptr1; shared_ptr ptr2;
1
vote
1 answer

Whether assigning smart pointer to _variant_t requires a manual AddRef()?

Here is an example snippet: _variant_t var; var.vt = VT_UNKNOWN; var.punkVal = unknownInterfaceSmartPointer; unknownInterfaceSmartPointer->AddRef(); // Question Statement // Setting unknownInterfaceSmartPointer to some other container Whether…
AksharRoop
  • 2,263
  • 1
  • 19
  • 29
1
vote
2 answers

When will the destructor be called?

#include #include class Token { public: Token() { std::cout << "Token()"; } ~Token() { std::cout << "~Token()"; } }; template std::unique_ptr foo(T t0) { return std::unique_ptr(new T(t0)); }; int…
dajde
  • 13
  • 3
1
vote
2 answers

How to copy an array that has been initialized as an smartpointer?

I am using std::unique_ptr CPPPixelBuffer; to store pixel data of a texture as an array. This array is initialized in the constructor as followed: SIZE_T BufferSize = WorldTextureWidth * WorldTextureHeight *…
Schrello
  • 27
  • 5
1
vote
0 answers

How to manage vector of pointers in C++ where pointer is allocated by Lua

In the simple 2D Game Engine I am working. I want to define and script my entities using Lua and do all the heavy work in C++ (rendering, physics, etc.) To do this I have basic Entity class: class Entity { public: Entity() { …
kaktusas2598
  • 641
  • 1
  • 7
  • 28
1
vote
1 answer

std::vector> compile error

Something error with my code. I use forward declaration in my class , the std::unique_ptr work well. But the std::vector> cause a compile error. Has anyone encountered this situation before? Thank…