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

shared_ptr with given C-like allocation and deallocation functions

I was given an API for some library (nng to be exact) it has a C-like interface for allocating and deallocating a message object: int nng_msg_alloc(nng_msg **, size_t); void nng_msg_free(nng_msg *); I'm trying to create a C++ interface for the…
Omer Kawaz
  • 291
  • 1
  • 12
1
vote
0 answers

VS2010 C++ - problem casing based class pointer to derived class pointer

Using VS2010 and C++, I am using a supplier library to interface to their USB industrial camera. The library has an base abstract class for data stream sinks called GrabberSinkType, and one of derived classes from that is MediaStreamSink which deals…
nmw01223
  • 1,611
  • 3
  • 23
  • 40
1
vote
1 answer

segmentation fault when acessing attribute of an smart pointer to class, inside another class

i tried to make this: #include #include class B { public: std::string var; B() { var = "original"; } void print() { std::cout << "composition " << std::endl; } }; class…
Guinther Kovalski
  • 1,629
  • 1
  • 7
  • 15
1
vote
2 answers

Is it mandatory for destructor to use delete when managed via unique pointer?

If a c++ resource is managed via unique_ptr then does the destructor of the class need to free the heap memory it allocated or it gets free automatically when the unique_ptr goes out of scope? For eg. In below example if I plan to create a…
Helena
  • 444
  • 2
  • 15
1
vote
2 answers

How to define the operator= for a unique_ptr wrapper class?

I am trying to create a wrapper class for the std::unique_ptr, for now it just needs to support the basic operations for the unique_ptr, but in the future this would have more functionalities. template class Unique { public: …
1
vote
3 answers

Cannot assign int to member int of returned class

Not 100% sure whether my question is worded correctly as I don't fully understand my problem. For my course I need to create my own smart pointer to clean up after itself. Here's my code so far: Header: class Test { public: Test() …
Ben
  • 11
  • 1
1
vote
1 answer

Is there a way to cast a shared ptr to void pointer and then cast the void pointer back to shared pointer?

I have a shared pointer of objects throughout my application. Here is one example: std::shared_ptr texture = loadImageFromFile("someFile.png"); I am using a UI library called ImGui and this library has a concept of a texture ID, which is…
Gasim
  • 7,615
  • 14
  • 64
  • 131
1
vote
1 answer

How could I get address of the target object in smart pointer?

I'm trying to implement the linked list by indirect pointer, which introduced on the TED Talk. I refer to felipec's implementation on github and made an version by raw pointer, this is the github link. This is part of the full code, _find is a…
Mes
  • 177
  • 7
1
vote
2 answers

Why does for cycle in vector of unique_ptr require default delete?

I am working in vs2019 and following code worked fine: std::vector foos; // fills vector for (Foo* foo : foos) { //do stuff } However, if i try to use unique_ptr like this: std::vector> foos; // fills vector for…
Lubomír Grund
  • 145
  • 1
  • 13
1
vote
1 answer

Why do I need Boost.SmartPtr for the C++ compiler that supports C++11 and later?

The boost C++ library is a famous sandbox for the language and Standard Library features that absorbed with each new version of the Standard C++. However boost components that eventually became a part of the Standard are still present in boost. One…
nickolay
  • 3,643
  • 3
  • 32
  • 40
1
vote
1 answer

C++11 vector with smart pointer

I read a lot of documentation about vector modern usage. One of the common thing appearing is, "you can replace every push_back by emplace_back". Is it true ? I'm unsure, and the fact is I don't get the idea with a smart pointer. So, is there a…
1
vote
2 answers

How do I properly use a dynamically-allocated opaque pointer in a scoped pointer class?

Background I'm working with the Intel IPP Cryptographic Libraries for testing. They define several opaque structs used for shared contexts over things like hashing and encryption which, of course, cannot be directly instantiated. To initialize one…
Mark Cohen
  • 13
  • 2
1
vote
1 answer

Why does calling a function on seperate lines change the result in c++?

It seems that for some reason when I try to call two functions on the same line, the first function receives an nullptr from ".get()" as the first argument getSomePtr(someUniquePtr.get(), someArray)->moveUniquePtr(std::move(someUniquePtr)); But…
Matoy
  • 23
  • 3
1
vote
1 answer

C26414 issue with using CRecordset

I have seen a similar discussion here (C++ Code Analysis in Visual Studio Community 2019 produces warnings C26486 and C26414) where it refers to using std::move but I am not sure if this is what I need to do. I turned CRecordset *pRecords = new…
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
1
vote
1 answer

Debug assertion failure - C++, using smart pointers

I have been trying to debug this for a while now without any luck. I was hoping to get some help here. Apologies if my question isn't relevant or something, I'm new. So basically what I have is: #include template class Node…
somenpc323
  • 13
  • 3