关于 unique_ptr 行为与 std::move 的特定用法的问题

问题描述 投票:0回答:1

基于排序操作,以下代码在 C++20 中是否定义良好,或者是否具有未定义的行为?

#include <iostream>
#include <memory>

using namespace std;

struct A {
  A(int i) : a_(i) {}
  int Foo(unique_ptr<A>) { return a_; }
  int a_ = 0;
};

int main() {
  auto a_ptr = make_unique<A>(10);
  cout << a_ptr->Foo(std::move(a_ptr)) << '\n';
}

使用 C++17,本文提出了更严格的表达式求值顺序。

a->b
订购(
a
b
之前)是其中的一部分。

这是否意味着在这种情况下

a_ptr->Foo(std::move(a_ptr))
应按如下顺序排列:

A* a_ptr_raw = a_ptr.operator->();
a_ptr_raw->Foo(std::move(a_ptr));

这将使这个定义明确。

c++ c++11 unique-ptr move-semantics
1个回答
1
投票

是的,它定义明确......但不直观。

您引用的论文的作者似乎想让一些示例正确工作(即让它们按照人们直观的期望进行操作),例如这个:

std::string s = “but I have heard it works even if you don’t believe in it”;
s.replace(0, 4, “”).replace(s.find(“even”), 4, “only”).replace(s.find(“ don’t”), 6, “”);
assert(s == “I have heard it works only if you believe in it”); // OK.

在此过程中,它使一些令人困惑的陈述“明确定义”,但这并没有使它们变得不那么混乱。你的例子让人想起臭名昭著的:

*x = *x++ + 1;
© www.soinside.com 2019 - 2024. All rights reserved.