c++ - 删除从函数返回的唯一指针?

标签 c++ c++11 unique-ptr

如果我有一个返回 unique_ptr 的函数 source,并且我有一个调用 source 的函数 sink > 通过以下方式,它可以正常工作 [clang]。

但是行为是未定义的吗?或者一切都是共生的?

class Foo {
  ...
  bool isValid() { return true; }
  ...
}

std::unique_ptr<Foo> source() {
  auto foo = std::make_unique<Foo>();  // let's pretend this is C++14?
  /* ... initialize foo */
  return foo;
}

void sink() {
  if (source()->isValid()) {
    /* do something */
  }
  /* ... */
}

仅在该行使用 unique_ptr 是否有效? 理论上什么时候应该销毁对象?在那条线之后?在函数结束时?

最佳答案

是的,您的代码有效。未命名的临时 unique_ptrsource 返回将在创建它的完整表达式的末尾被销毁,在本例中为 if 中的条件声明。

来自 N3337,§12.2/3 [class.temporary]

... Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. ...

来自§6.4/1 [stmt.select]if 的语法声明是

Selection statements choose one of several flows of control.

  selection-statement:
      if ( condition ) statement
      ...
  condition:
      expression
      ...

请注意 return std::move(foo);不需要,可以写return foo;unique_ptr将是 automatically moved .

关于c++ - 删除从函数返回的唯一指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31659123/

相关文章:

c++ - 在 CLion 中使用 OpenGL 时出现未定义引用错误

c++ - make_unique、工厂方法或客户端 API 的不同设计?

c++ - 来自元组的构造函数参数

c++ - 从 C++ 中的函数返回动态分配的缓冲区的最佳模式是什么?

c++ - new int[100] 和 new int[100]() 的区别;

c++ - 键盘 Hook ......没有得到小写或大写字符

c++ for循环不同的方式

c++ - 映射中的c++/元素通过退出函数神秘地消失

c++ - 比较两个 C++ 迭代器的性能成本

c++ - 可变参数 lambda 捕获的解决方法