C++ smart pointer const correctness

shared_ptr<T> and shared_ptr<const T> are not interchangable. It goes one way – shared_ptr<T> is convertable to shared_ptr<const T> but not the reverse.

Observe:

// f.cpp

#include <memory>

int main()
{
    using namespace std;

    shared_ptr<int> pint(new int(4)); // normal shared_ptr
    shared_ptr<const int> pcint = pint; // shared_ptr<const T> from shared_ptr<T>
    shared_ptr<int> pint2 = pcint; // error! comment out to compile
}

compile via

cl /EHsc f.cpp

You can also overload a function based on a constness. You can combine to do these two facts to do what you want.

As for your second question, MyExample<int> probably makes more sense than MyExample<const int>.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)