我想创建一个可以区分临时对象和非常量非临时对象的类 Bar。根据this (about 25% down the page) ,如果第二个 StealPointer 采用 const 引用(在我的例子中指向一个指针),我可以摆脱这个,但在我的代码中它只使用 StealPointer(Foo*&& foo) 版本,不管它是如何调用的。
class Foo {};
class Bar {
public:
// For when StealPointer(new Foo()); is called. Bar instance then owns the
// pointer.
void StealPointer(Foo*&& foo) {} // Get the temporaries only.
// For when a Foo* already exists and is passed in StealPointer(my_foo_ptr);
// Takes ownership and invalidates the pointer that the caller once had.
void StealPointer(Foo*&) {} // Get lvalues only.
};
我可以这样做吗?有没有一种方法只需要一个功能就可以做到这一点?如果重要的话,Bar 将把指针存储在 unique_ptr 中,我想避免传入 unique_ptr 或让调用者使用 std::move 执行某些操作的额外语法。我不能只通过引用传递指针,因为 Foo* 类型的临时变量不能转换为 Foo*&。
最佳答案
将您的函数模板化,让 std::unique_ptr
为您操心这些细节。
template <typename Ptr>
void StealPointer(Ptr&& p) // a universal reference, matches *any* type of value
{
uniqptr = std::move(p); // Works for both rvalues and lvalues
}
关于c++ - 区分函数签名中的临时对象和非临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689802/