Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unique_ptr constant reference

I am trying to migrate a solution using pointers to one using unique_ptr, to simplify resource handling. I am aware of move semantics and the the use of std::move() to work with unique_ptr's.

Presently I have a function with the signature int foo(const T2DMatrix* m) and I call this using a dynamically allocated 2D-Matrix object. The function foo requires only read-only access to T2DMatrix class, hence the const argument. Now, I've migrated this to int foo(unique_ptr<const T2DMatrix>& m). From a different function, process(), which has a unique_ptr<T2DMatrix> object (created using a factory function), I want to pass the object to foo as the parameter. However, the compiler doesn't allow me to do so. Please note, I do not want to transfer ownership of the object from process() to foo(), hence the use of references. Calling foo() with a unique_ptr<const T2DMatrix> works fine, however the const guarantee would not be enforced if I change the function signature.

Note: one solution I've found is to create a new unique_ptr<const T2DMatrix> object in process(), transfer ownership to it from the original unique_ptr<T2DMatrix> object using std::move(), pass it to foo(), and again transfer ownership in process(). But this hardly seems the ideal solution.

Please suggest the equivalent of the pointer solution which was allowing me to pass a T2DMatrix* argument to const T2DMatrix* parameter. I tried using msvc2012, msvc2013 and g++4.8, all with the same results.

like image 410
Ankur Kanoria Avatar asked Feb 27 '14 09:02

Ankur Kanoria


People also ask

What does unique_ptr mean in C++?

(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Do you need to delete a unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.

Can unique_ptr be assigned?

It can be assigned: class owner { std::unique_ptr<someObject> owned; public: owner() { owned=std::unique_ptr<someObject>(new someObject()); } };


1 Answers

If the function does not require ownership, pass a plain reference instead of a reference to unique_ptr:

int foo(T2DMatrix const& m);


std::unique_ptr<T2DMatrix> matrixptr;
[...]
foo(*matrixptr);

There's no need to artificially constrain foo to unique_ptrs if the function does not care about ownership anyway.

like image 118
ComicSansMS Avatar answered Oct 11 '22 13:10

ComicSansMS