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

2412 questions
1
vote
1 answer

Abstract class inheritance and smart pointer containers

I am creating an abstract geometry class that has children classes. However, I want that the class RightCircularCone also has its own private variables that define its apex coordinates, such that the abstract class is not unnecessary big in memory…
Loek Janssen
  • 261
  • 1
  • 4
  • 15
1
vote
2 answers

How to implement factory+decorator pattern in c++11

I decided to study/translate Head First Design Patterns' Java code to C++11, and I was able to implement most of the patterns using automatic memory management thanks to smart pointers. However, I have a problem with one of the examples. Here is my…
mty
  • 700
  • 6
  • 15
1
vote
1 answer

Smart pointers with a resource manager that lets objects "borrow" resources

I am somewhat new to the smart pointer world of C++ 11. I have been doing memory management manually and decided to dive into smart pointers. However, there is somewhat of a confusion though when it comes to managers I define a manager as An object…
Serguei Fedorov
  • 6,947
  • 9
  • 55
  • 86
1
vote
1 answer

Finding weak_ptrs referring to a shared_ptr

Is there a way to find out the number of weak_ptrs a shared_ptr is being referred by? unique()/use_count() could be used for finding the shared_ptrs but is there a similar construct for finding the referring weak_ptrs. I want to release the resource…
Arun
  • 2,808
  • 3
  • 26
  • 39
1
vote
2 answers

Accelerated C++ 14-5: Custom string class and reference counter works for one constructor but not another

For those of you familiar with the book Accelerated C++, I was writing a solution to problem 14-5 and came across some interesting behavior that I can't explain. The problem involves using custom string and pointer/reference counter classes to…
Adam27X
  • 869
  • 1
  • 7
  • 16
1
vote
2 answers

Seg. fault with std::unique_ptr and ctor

For a parser I am actually implementing I partially have these private functions within the parser: Parser private methods: Token const* current_token() const; Token const* next_token(); Token const* peek_token(); …
1
vote
2 answers

Approximation of a polymorphic local variable

I would like to make the runtime type of a local variable depend on some condition. Say we have this situation: #include class Base{ public: virtual void foo()=0; }; class Derived1 : public Base { virtual void foo(){ …
isarandi
  • 2,518
  • 21
  • 32
1
vote
0 answers

is it possible to search for C++ statement by types and operands?

Is there a method or tool for searching in C++ based on types in an expression? For example, let's say we have: m_polydata = Normals->GetOutput(); //NOTE: POSSIBLE LEAK!! // decltype(m_polydata) is vtkSmartPointer
peter karasev
  • 2,406
  • 1
  • 26
  • 37
1
vote
2 answers

Correct way to cast using unique_ptr

I'm trying to compile the following code but I get this error: error: no viable conversion from 'unique_ptr' to 'unique_ptr' What I'm trying to do is create a smart pointer that wraps some objects and then use them as listeners. #include…
oscarm
  • 2,484
  • 5
  • 35
  • 72
1
vote
6 answers

Automatically converting an A* into a B*

Suppose I'm given a class A. I would like to wrap pointers to it into a small class B, some kind of smart pointer, with the constraint that a B* is automatically converted to an A* so that I don't need to rewrite the code that already uses A*. I…
Xavier Nodet
  • 4,734
  • 2
  • 33
  • 48
1
vote
1 answer

How to create an array of smart pointers?

I have created a class, which reference some members as smart pointers, I want to create an array of this class but I get different types of errors class ConnectionType : public SimpleRefCount { public: Ptr txMstrSocPtr;…
Fouda
  • 261
  • 1
  • 2
  • 12
1
vote
3 answers

c++ swapping unique_ptr's

New to this kind of stuff, probably doing something wrong, but - I have 3 members std::unique_ptr currentWeapon; std::unique_ptr weaponSlotOne; std::unique_ptr weaponSlotTwo; Gun is a base class that has other derived classes such as…
Evan Ward
  • 1,221
  • 1
  • 10
  • 19
1
vote
3 answers

Member variable pointers to COM objects

Is there any problem with keeping member variable pointer refernces to COM objects and reussing the reference through out the class in C++. Is anybody aware of a reason why you would want to call .CreateInstance every time you wanted a to use the…
Robben_Ford_Fan_boy
  • 7,544
  • 7
  • 55
  • 80
1
vote
0 answers

container for derived template classes

I have the following classes: template class PacketMember { public: PacketMember() { } // Some non-virtual member functions }; template class NormalMember : PacketMember { public: }; template
moki
  • 2,259
  • 1
  • 19
  • 39
1
vote
2 answers

Using smart pointers as a class member

I have been reading up on smart pointers and recently in class my TA said that we should never use raw pointers. Now, I've done a lot of reading online and looked at different questions on this website but I'm still confused on some aspects of smart…
Wes
  • 41
  • 1
  • 6
1 2 3
99
100