Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
hamed1soleimani Avatar asked Sep 28 '26 12:09

hamed1soleimani


1 Answers

There are two issues:

  • How to constify the referent of a unique_ptr.
  • How to pass a non-owning pointer to a function.

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!
like image 150
Cheers and hth. - Alf Avatar answered Sep 30 '26 04:09

Cheers and hth. - Alf