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

Does make_shared ignore explicit specifier?

Consider the following example: #include #include struct A { explicit A(int x) { std::cout << x << std::endl; } }; void Foo(A ) {} std::shared_ptr Foo2(int x) { // why does this work? return…
RoQuOTriX
  • 2,871
  • 14
  • 25
1
vote
1 answer

std::pair gives "no matching function call" error in combination with const std:unique_ptr

I stumbled across a behaviour of std::make_pair that I do not understand. Given the following code #include using namespace std; #include #include class TestClass { public: TestClass(const std::string&…
LosConikos
  • 93
  • 6
1
vote
1 answer

Is this proper usage of std::shared_ptr?

I was wondering if the following is correct usage of a std::shared_ptr. All I want to do with the originally created pointer is add it onto the vector on class A, which will be later on retrieved class A { public: void AddToVec(std::shared_ptr
Yorda
  • 11
  • 1
1
vote
2 answers

Can a std::unique_ptr be reassigned such that its old value is destroyed *before* the new one is constructed?

I'm interested in updating an old personal project to modern C++. I appreciate how RAII simplifies cleanup: instead of making a new object and remembering to delete it before every return point in a function, just make_unique and it will be…
Remy
  • 401
  • 2
  • 19
1
vote
2 answers

Segmentation fault when passing std::shared_ptr to subclass

The following code illustrates my intent: https://godbolt.org/z/dhhascnoo #include #include #include #include #include class Dbg { protected: bool enabled; public: Dbg() : enabled(false) {} …
jkang
  • 483
  • 7
  • 19
1
vote
1 answer

Creating new Rc instances without taking ownership

Say I have the following code: use std::rc::Rc; struct Struct {} struct Pair { first: Rc, second: Rc } fn pair_lists(vec:Vec) -> Vec { let mut pair = Vec::new(); for i in 0..vec.len() { for j…
Alex Coleman
  • 607
  • 1
  • 4
  • 11
1
vote
0 answers

Calling function from outside the class with existing class member pointer

Im stuck with an issue connected to smart pointers. I have a class Property which inherits from class Cell and I want to pass current class member pointer to Player class member function. class Player { private: …
Leszek
  • 47
  • 1
  • 1
  • 6
1
vote
2 answers

Raw pointer to shared_ptr bug

I'm working on a image treating application. In summary, I have a byte buffer which stores the image data, so I can use this array to handle the image easily in wx widgets and OpenCV. I planned to store this byte buffer in a shared_ptr as it will be…
1
vote
1 answer

Why does std::weak_ptr::lock return empty shared pointer here?

I'm trying to create an AABBTree structure where each node knows its parent and children. Within my AABBTreeNode class, the parent is stored as a std::shared_ptr and the children as a std::vector>. This is…
Roland Deschain
  • 2,211
  • 19
  • 50
1
vote
2 answers

Replacing/refactoring of naked pointers

I want to replace traditional naked pointer usage in a class inheritance situation. Example for what I mean: #include #include #include using namespace std; class Base { public: void doBaseStuff () { cout <<…
1
vote
2 answers

Why does shared_ptr not delete its memory?

int main(){ int* iptr; { std::shared_ptr sptr = std::make_shared(12); iptr = sptr.get(); } std::cout << *iptr; return 0; } Output 12 I was expecting that the content to which iptr points, would have been…
hsynydn
  • 27
  • 5
1
vote
0 answers

C++ `enable_shared_from_this` and `shared_From_this()` not compiling or running

I am having a hard time trying to compile the following code using clang compiler. I am not sure if I am using enable_shared_from_this and shared_From_this() in the right way, or breaking rule inadvertently. Can someone point me out what is exactly…
kishoredbn
  • 2,007
  • 4
  • 28
  • 47
1
vote
2 answers

Templatize downcasting to the derived class and call the corresponding method

I have a routine in the main.cpp where user will specify which mode to execute in the program. Once the mode is specified, the corresponding block will be executed - first downcast the parent solver to the child solver and call the associated solve…
livemyaerodream
  • 890
  • 6
  • 19
1
vote
1 answer

How to avoid copy assignment operator c++ for a shared pointer

Consider the line below to create an object foo of class creature: foo = creature(choice); This creates a temporary creature object before assigning it to foo. Which also means that the destructor will be called. If I don't want this to happen, and…
badri
  • 575
  • 2
  • 8
  • 22
1
vote
1 answer

Best Practices? Converting from pointers to Unique_Ptrs

I am trying to convert from naked pointers to smart pointers. But I am not quite sure how to keep currentBar (Who will also be located in myBars) while using unique pointers Class Foo { public: Bar* getCurrentBar(); //!! other stuff not…
Questor
  • 129
  • 6