Permalink C ++ unique_ptr

I am trying to port a solution using pointers to one using unique_ptr to simplify resource handling. I know about the semantics of moving and using std::move() to work with unique_ptr.

I currently have a function with an int foo(const T2DMatrix* m) signature int foo(const T2DMatrix* m) , and I call it using a dynamically allocated 2D-Matrix object. The foo function requires only read-only access to the T2DMatrix class, hence the const argument. Now I ported it to int foo(unique_ptr<const T2DMatrix>& m) . From another process() function that has a unique_ptr<T2DMatrix> object (created using the factory function), I want to pass the object to foo as a parameter. However, the compiler does not allow me to do this. Please note: I do not want to transfer ownership of the object from process() to foo() , hence the use of links. Calling foo () using unique_ptr<const T2DMatrix> works fine, however the const guarantee will not apply if I change the function signature.

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

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

+7
c ++ pointers c ++ 11 const unique-ptr
source share
1 answer

If the function does not require ownership, pass a regular link instead of a unique_ptr :

 int foo(T2DMatrix const& m); std::unique_ptr<T2DMatrix> matrixptr; [...] foo(*matrixptr); 

There is no need to artificially restrict foo to unique_ptr if the function still doesn't care about ownership.

+19
source share

All Articles