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

标签 c++ c++11 rvalue-reference temporary

我想创建一个可以区分临时对象和非常量非临时对象的类 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/

相关文章:

c++ - 带有可移动、不可复制参数的 std::thread

c++ - 字符指针(由 new 分配)

c++ - 这里如何使用最小堆来解决这个问题

C++ 将流操纵器复制到其他流

c++ - 什么时候 std::move 是多余的?

C++0x : rvalue reference versus non-const lvalue

c++ - Qt-有没有办法优先调整子窗口小部件的大小

c++ - 迭代/递归

c++11 - 在 C++11 中使用初始化列表初始化二维向量

c++ - GCC 拒绝使用 enum-base 的简单声明; clang 接受它——这是正确的吗?