std :: move的未定义行为 [英] Undefined behavior with std::move

查看:239
本文介绍了std :: move的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从cppreference的移动页面

From the move page of the cppreference


除非另外指定,否则将已移走
的所有标准库对象置于有效但未指定的状态。也就是说,只有
对象没有先决条件,例如赋值
运算符,才可以在对象从$

$ b $中移出后安全地使用该对象。 b

因此,在同一页上的示例中,以下代码被认为是未定义的行为

So, from the example on the same page, this code below is considered undefined behaviour

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

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

MSVC will output nothing on the console, but if I do this

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

将输出10。这是否有发生的原因?还是总是不确定的行为?

will output 10. Is there a reason why this happens? Or is it always undefined behavior?

推荐答案

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

Unspecified does not mean undefined.

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

According to the C++11 standard, section 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(),该前提条件还要求字符串为非空。有效字符串可以为空。

As the object is in a valid state, you can stream it to an output, as streaming has no additional preconditions. However what is printed is unspecified, so it may just print nothing, or print that your father smells of elderberries. What you can not safely do is use a function with additional preconditions such as back() which additionally requires the string to be non-empty. Valid strings can be empty.

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

Containing the old value is a perfectly acceptable option for the unspecified but valid state. In case of fundamental types such as int a simple copy is just the most efficient way to perform a move.

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

It should also be noted that int is not a standard library object, but a fundamental type (as defined in section 3.9.1). Therefore your quote does not apply.

这篇关于std :: move的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆