简体   繁体   English

C ++ unique_ptr常数参考

[英]C++ unique_ptr constant reference

I am trying to migrate a solution using pointers to one using unique_ptr, to simplify resource handling. 我正在尝试使用指向使用unique_ptr的指针的解决方案,以简化资源处理。 I am aware of move semantics and the the use of std::move() to work with unique_ptr's. 我知道移动语义以及使用std::move()与unique_ptr一起使用。

Presently I have a function with the signature int foo(const T2DMatrix* m) and I call this using a dynamically allocated 2D-Matrix object. 目前,我有一个签名为int foo(const T2DMatrix* m)的函数,并使用动态分配的2D-Matrix对象调用此函数。 The function foo requires only read-only access to T2DMatrix class, hence the const argument. 函数foo仅需要对T2DMatrix类的只读访问权限,因此需要const参数。 Now, I've migrated this to int foo(unique_ptr<const T2DMatrix>& m) . 现在,我将其迁移到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. 从另一个函数process() ,它具有一个unique_ptr<T2DMatrix>对象(使用工厂函数创建),我想将该对象作为参数传递给foo。 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. 请注意,我不想将对象的所有权从process()转移到foo() ,因此要使用引用。 Calling foo() with a unique_ptr<const T2DMatrix> works fine, however the const guarantee would not be enforced if I change the function signature. 使用unique_ptr<const T2DMatrix>调用foo()可以正常工作,但是如果我更改函数签名,则不会强制执行const保证。

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(). 注意:我发现的一种解决方案是在process()中创建一个新的unique_ptr<const T2DMatrix>对象,使用std::move()从原始的unique_ptr<T2DMatrix>对象将所有权转让给它,并将其传递给foo() ,然后再次转让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. 请提出与指针解决方案等效的建议,该方案允许我将T2DMatrix *参数传递给const T2DMatrix *参数。 I tried using msvc2012, msvc2013 and g++4.8, all with the same results. 我尝试使用msvc2012,msvc2013和g ++ 4.8,所有结果相同。

If the function does not require ownership, pass a plain reference instead of a reference to unique_ptr : 如果该函数不需要所有权,则传递一个普通引用而不是对unique_ptr的引用:

int foo(T2DMatrix const& m);


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

There's no need to artificially constrain foo to unique_ptr s if the function does not care about ownership anyway. 如果函数无论如何都不在乎所有权,则无需人为地将foo约束为unique_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM