区分函数签名中的临时对象和非临时对象?

Distinguish between temporaries and non-temporaries in function signature?

我想创建一个 class 可以区分临时对象和非常量非临时对象的栏。根据 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
}