What does the standard library guarantee about self move assignment?(标准库对自移动分配有什么保证?)
问题描述
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 的实现允许假设 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 只需在赋值前等于rv 和 rv 不引用同一个对象.无论如何,在赋值之后 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 仍然必须满足使用它的库组件的要求,无论 t 和 rv 是否引用同一个对象.
rvmust still meet the requirements of the library component that is using it, whether or nottandrvrefer to the same object.
这篇关于标准库对自移动分配有什么保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:标准库对自移动分配有什么保证?
 
				
         
 
            
        基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				