Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top