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
是否引用同一个对象.
rv
must still meet the requirements of the library component that is using it, whether or nott
andrv
refer to the same object.
这篇关于标准库对自移动分配有什么保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:标准库对自移动分配有什么保证?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01