Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared pointer from const pointer

Tags:

c++

c++11

Suppose that I have a function that returns

const MyType*

Can I capture the result into a shared_ptr? How?

like image 984
pistacchio Avatar asked Jun 10 '26 17:06

pistacchio


1 Answers

You can use the default constructor to do it. By the way there's a catch: beware of the const T - T pointer sharing!

#include <iostream>
#include <memory>
using namespace std;

class MyType {
    public:
};

const MyType* fun() {
    return new MyType();
}

int main() {

    {
        shared_ptr<const MyType> new_ptr(fun());

        // Use your pointer..

        shared_ptr<MyType> other_ptr(new MyType());
        shared_ptr<const MyType> other_ptr2 = other_ptr; // T to const T, allowed

        shared_ptr<MyType> new_ptr2 = new_ptr; // const T to T - NOT ALLOWED
    }

    return 0;
}

http://ideone.com/OOPdLu

like image 82
Marco A. Avatar answered Jun 12 '26 10:06

Marco A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!