【问题标题】:Distinguish between temporaries and non-temporaries in function signature?在函数签名中区分临时对象和非临时对象?
【发布时间】: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


【解决方案1】:

将您的函数模板化,让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
}

【讨论】:

  • 这很有趣。为什么在使用左值作为常量引用调用时模板解释类型,但没有模板它更愿意使用右值引用签名?
  • @Chet &amp;&amp; 与模板一起使用时具有不同的含义。有关说明,请参阅 this
  • 我需要一些时间来消化那个参考,但这正是我的目标。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2016-01-30
  • 2015-12-14
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多