Suppose that I have a function that returns
const MyType*
Can I capture the result into a shared_ptr? How?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With