Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared pointers and const correctness

Which is the correct way to extend the const correctness of a class to its pointed members? In the example code, is the constant version of the get method going to create an std::shared_ptr whose reference counter is the same as the internal member m_b, or is it starting again counting from 0?

class A
{
    std::shared_ptr< B > m_b;

public:

    std::shared_ptr< const B > get_b( ) const
    {
        return m_b;
    }

    std::shared_ptr< B > get_b( )
    {
        return m_b;
    }
}
like image 615
nyarlathotep108 Avatar asked Mar 21 '16 11:03

nyarlathotep108


People also ask

What is const-correctness in C?

In C, C++, and D, all data types, including those defined by the user, can be declared const , and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified.

What is the difference between shared pointer and weak pointer?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.

What is the point of shared pointers?

In C++, a shared pointer is one of the smart pointers. The shared pointer maintains a reference count which is incremented when another shared pointer points to the same object. So, when the reference count is equal to zero (i.e., no pointer points to this object), the object is destroyed.

Are shared pointers smart pointers?

Shared pointers are smart pointers that keep a count of how many instances of the pointer exist, and only clean up the memory when the count reaches zero. In general, only use shared pointers (but be sure to use the correct kind--there is a different one for arrays).


1 Answers

shared_ptr will always preserve reference counts when you construct from another shared_ptr; the only way to use it unsafely is to construct from a raw pointer: shared_ptr<...>(my_ptr.get()) // don't do this .

You may also be interested in the propagate_const wrapper, which is in the Library Fundamentals TS v2 so will probably be available in your implementation quite soon.

like image 71
ecatmur Avatar answered Sep 24 '22 07:09

ecatmur