标准库对自移动分配有什么保证?

2022-01-07 00:00:00 c++ c++11 stl move-semantics

C++11 标准对与标准库相关的自移动赋值有什么看法?更具体地说,selfAssign 的作用是什么(如果有的话)?

What does the C++11 standard say about self move assignment in relation to the standard library? To be more concrete, what, if anything, is guaranteed about what selfAssign does?

template<class T>
std::vector<T> selfAssign(std::vector<T> v) {
  v = std::move(v);
  return v;
}

推荐答案

17.6.4.9 函数参数 [res.on.arguments]

17.6.4.9 Function arguments [res.on.arguments]

1 以下每一项都适用于定义的函数的所有参数在 C++ 标准库中,除非另有明确说明.

1 Each of the following applies to all arguments to functions defined in the C++ standard library, unless explicitly stated otherwise.

...

  • 如果函数参数绑定到右值引用参数,则实现可能会假定此参数是对这个论点.[注意:如果参数是泛型参数表格 T&&并且绑定了类型 A 的左值,参数绑定到左值引用 (14.8.2.1) 因此不包括在前面的句子.― end note ] [ 注意:如果程序将左值转换为xvalue 同时将该左值传递给库函数(例如通过使用参数 move(x)) 调用函数,程序是有效地要求该函数将该左值视为临时值.该实现可以自由地优化掉别名检查如果参数是左值,则可能需要.――尾注]

所以,std::vector::operator=(vector&& other) 的实现允许假设 other 是一个原值.如果 other 是纯右值,则无法进行自移动赋值.

So, the implementation of std::vector<T, A>::operator=(vector&& other) is allowed to assume that other is a prvalue. And if other is a prvalue, self-move-assignment is not possible.

可能发生的事情:

v 将处于无资源状态(0 容量).如果 v 已经有 0 容量,那么这将是一个空操作.

v will be left in a resource-less state (0 capacity). If v already has 0 capacity, then this will be a no-op.

更新

最新工作草案,N4618 已被修改以明确说明在 MoveAssignable 要求中的表达式:

The latest working draft, N4618 has been modified to clearly state that in the MoveAssignable requirements the expression:

t = rv

(其中rv 是一个右值),如果t,t 只需在赋值前等于rvrv 不引用同一个对象.无论如何,在赋值之后 rv 的状态是未指定的.还有一个额外的说明需要进一步说明:

(where rv is an rvalue), t need only be the equivalent value of rv prior to the assignment if t and rv do not reference the same object. And regardless, rv's state is unspecified after the assignment. There is an additional note for further clarification:

rv 仍然必须满足使用它的库组件的要求,无论 trv 是否引用同一个对象.

rv must still meet the requirements of the library component that is using it, whether or not t and rv refer to the same object.

相关文章