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

Optimization - returning filtered elements as std:vector or std::vector> what is better and why?

I have some doubts about optimization regarding storing elements in vectors and getting information from them. Lets see the example struct Entity { public: Entity() = default; bool isActive = false; std::vector
drDzX
  • 11
  • 1
1
vote
0 answers

Not getting double free or corruption error on running program

I have written the following program which should give runtime error of double free corruption. #include #include using namespace std; int main() { shared_ptr shared3(new int); *shared3 = 9; int *raw =…
1
vote
3 answers

How can I retrieve the return value of pclose when the unique_ptr is destroyed?

As @user17732522 pointed out that the deleter of std::unique_ptr is supposed to be callable with exactly one pointer as argument. How can I retrieve the return value of pclose when the unique_ptr is destroyed? This code snippet does not…
John
  • 2,963
  • 11
  • 33
1
vote
2 answers

Use a unique_ptr as an opaque object id

I'm hiding the implementation details of third party C++ graph library (LEMON graph library) from my project by doing the following : API.h file class Node; using NodeId = unique_ptr; class ProgramGraph { private: class ProgramGraphImpl; …
ihi
  • 107
  • 1
  • 9
1
vote
1 answer

Pass reference to function that takes `std::unique_ptr`

I have a reference to my object of type MyType, but I need to call a function, say myFunction that takes a std::unique_ptr. What is the correct way to call myFunction? My attempt below seems to cause an "invalid pointer" error: #include…
Antonio
  • 355
  • 1
  • 2
  • 13
1
vote
2 answers

"auto" keyword: How to customize it?

Title is vague, I know. Consider this: template using Ref = std::shared_ptr; template using StrongRef = std::shared_ptr&; struct Person { std::string m_name; Person(const std::string& l_name) : m_name(l_name)…
1
vote
1 answer

why the raw pointer get by std::unique_ptr's get() can not delete the object and how is that implemented

As the following code presents, I tried to delete the object by the raw pointer get from a unique_ptr. But, as the output shows, the complier reported errors. However, for raw pointers, we can do this int *p1 = new int{100}; int* p2 = p1; delete…
amont
  • 81
  • 8
1
vote
1 answer

Smart pointers cast c++17 apple clang

I'm trying to use arrays in smart pointers, but when I cast smart_ptr to weak_ptr using Apple clang I get an error (I use -std=c++17). error: cannot initialize a member subobject of type 'std::weak_ptr::element_type *' (aka 'int (*)[]') with…
s1ava
  • 13
  • 2
1
vote
1 answer

static_cast() works but static_pointer_cast() does not?

When I write a class like this static_cast() calls the custom conversion operator. But static_pointer_cast() does not compile. Why is that, and what do I need to do to make it work? class A{ //class implementation operator int(){ return…
flxh
  • 565
  • 4
  • 19
1
vote
2 answers

(C++) How to write a clone method for a class which has a unique pointer as a data member?

I have the following set up: class Base { private: // data members public: // methods // pure virtual methods virtual Base* clone() const =0; } class Derived : public Base{ private: // more data members public: // more methods // pure virtual…
twj
  • 35
  • 6
1
vote
0 answers

error: no 'operator++(int)' declared for postfix '++'

Here the code snippet: #include #include int func() { int i = 0; i++; return i; } int main() { auto foo = [sp=std::make_shared(1)](){ int num = *sp++; return num;}; //no 'operator++(int)' declared for…
John
  • 2,963
  • 11
  • 33
1
vote
1 answer

"Default delete" errors when trying to use unique_ptr with vectors for polymorphism in C++

I'm relatively new to C++, and I'm hoping someone can help me resolve an issue I'm having with unique_ptr and vectors. Essentially I'm trying to use polymorphism so that I have a vector of type "Base", which is an abstract class (pure virtual). I'm…
N A
  • 51
  • 4
1
vote
3 answers

Move object from local variable to std::shared_ptr

Please note that with the words "object" and "move" in the title, I do not mean the C++-specific concepts of what an object is and what it means to move an object. I have a local variable of a pretty simple struct type where I accumulate some values…
Niko O
  • 406
  • 3
  • 15
1
vote
1 answer

Is providing a deleter explicitly required when storing array types inside smart pointers?

According to this paper, one of the common mistakes developers make ( #3 ) is using a smart pointer with array types; Mainly because the operator delete will be called instead of delete[], leaving the program with a memory leak. Depite that; looking…
Dávid Tóth
  • 2,788
  • 1
  • 21
  • 46
1
vote
1 answer

C2248 error when using smart pointers in singleton class

In below code I'm having C2248 error. When I replace smart pointers with the raw pointers it compiles. However I want to use smart pointer std::shared_ptr<> object. How can I correct this error when using smart pointer? #include
Mehmet B.
  • 17
  • 5