C++ smart pointer const correctness

后端 未结 5 1197
你的背包
你的背包 2020-12-24 10:56

I have a few containers in a class, for example, vector or map which contain shared_ptr\'s to objects living on the heap.

For example

template 

        
5条回答
  •  误落风尘
    2020-12-24 11:29

    shared_ptr and shared_ptr are not interchangable. It goes one way - shared_ptr is convertable to shared_ptr but not the reverse.

    Observe:

    // f.cpp
    
    #include 
    
    int main()
    {
        using namespace std;
    
        shared_ptr pint(new int(4)); // normal shared_ptr
        shared_ptr pcint = pint; // shared_ptr from shared_ptr
        shared_ptr 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 probably makes more sense than MyExample.

提交回复
热议问题