我想要创建一个类栏,可以区分临时人员和非临时人员。根据这个(大约25%下页),如果第二个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*&。
发布于 2016-01-09 05:15:47
让您的函数模板化,让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
}https://stackoverflow.com/questions/34689802
复制相似问题