【发布时间】:2016-04-13 21:19:58
【问题描述】:
我想创建一个可以区分临时对象和非常量非临时对象的类 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*&。
【问题讨论】:
-
我假设 Bar 是一个结构或者 StealPointer 方法应该是公共的。
-
template <typename Ptr> void StealPointer(Ptr&& foo) : uniqptr{std::move(foo)} {};我相信会处理您担心的每一个案件 -
你可以这样做,或者你可以只拥有一个接受右值引用的函数,如果你用
lvalue调用StealPointer,你将不得不用std::move包装它,否则它将是编译时错误。 -
@TrevorHickey - 是的,公开的。在我试图简化的过程中被冲昏了头脑。
-
为什么要避免使用
unique_ptr参数?如果要承担所有权,这正是您的功能应该采取的措施。而且你的最后一句话没有多大意义。
标签: c++ c++11 rvalue-reference temporary