dimanche 5 mars 2017

initialize unique_ptr const reference from a unique_ptr

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?

Aucun commentaire:

Enregistrer un commentaire