gpt4 book ai didi

c++ - std::move 的未定义行为

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:57 24 4
gpt4 key购买 nike

来自move page的cppreference

Unless otherwise specified, all standard library objects that have been moved from are placed in a valid but unspecified state. That is, only the functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from

因此,从同一页面上的示例来看,下面的代码被认为是未定义的行为

vector<string> v_string;
string example = "example";
v_string.push_back(move(example));
cout << example << endl;

MSVC 将不会在控制台上输出任何内容,但如果我这样做

vector<int> v_int;
int number = 10;
v_int.push_back(move(number));
cout << number << endl;

将输出 10。是否有发生这种情况的原因?或者它总是未定义的行为?

最佳答案

未指定并不意味着未定义。

根据 C++11 标准,第 17.3.26 节:

valid but unspecified state an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type

当对象处于有效状态时,您可以将其流式传输到输出,因为流式传输没有额外的先决条件。然而, 打印的内容是未指定的,因此它可能什么都不打印,或者打印出你父亲闻到接骨木浆果的味道。您不能安全地做的是使用具有附加前提条件的函数,例如 back() ,它另外要求字符串为非空。有效字符串可以为空。

对于未指定但有效的状态,包含旧值是一个完全可以接受的选项。对于诸如 int 之类的基本类型,简单的复制只是执行移动的最有效方式。

还应注意 int 不是标准库对象,而是一种基本类型(如 3.9.1 节中所定义)。因此,您的报价不适用。

关于c++ - std::move 的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32346143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com