I initialized an unique_ptr with an Object. As i want to pass a reference of it to a function and don't let the function to change the object contents, I have to pass unique_ptr<const MyObject>& to it. But gcc 5.4 doesn't let me to initialize unique_ptr<const MyObject>& from uinque_ptr<MyObject>.
Example Code:
class Foo{public int x;};
unique_ptr<Foo> foo(new Foo());
foo->x = 5;
// User shouldn't be able to touch bar contents.
unique_ptr<const Foo>& bar = foo;
C++ error:
error: invalid initialization of reference of type ‘std::unique_ptr<const Foo>&’ from expression of type ‘std::unique_ptr<Foo>’
So is there any reasonable way to do it?
There are two issues:
constify the referent of a unique_ptr.The reasonable way to pass a non-owning pointer is to pass a raw pointer:
some_function( my_unique_ptr.get() );
Or if it can't be null then you can dereference the pointer and pass a reference,
some_function( *my_unique_ptr )
This means that the constification is pretty much irrelevant to the main issue, but still, here's how to do that also:
unique_ptr<Foo> p{ new Foo() };
unique_ptr<const Foo> q{ move( p ) }; // Moves ownership!
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