移动容器上的分配:以前包含的对象的状态
Move assignment on containers: state of previously contained objects
来自 another question (actually, rather this one,但前者是更好的参考),除了 20.5.5.15:
,我在标准中找不到合适的参考
Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.
对目标容器中先前包含的元素是否有任何要求,例如。 G。在分配前被销毁?
示例:
std::list<SomeClass> v1({10, 12});
std::list<SomeClass> v2({7});
v1 = std::move(v2);
for(auto sc : v2)
{
std::cout << sc << ' ';
}
虽然 GCC 根本没有输出任何东西(std::vector
和 std::list
类似),但会收到 10 12
作为输出合法(适当的 operator<<
提供)(例如通过交换内容接收,特别是不删除以前包含的对象)?
截至目前,我会说 "yes",但感觉不够确定可以依赖并且太好奇而不 post 一个问题...
如果合法,如果不立即销毁元素(例如,结果某些资源仍然保持打开状态,而开发人员希望它们关闭),任何开发人员都会出乎意料吗?
在[container.requirements.general]
中,我们看到
All existing elements of a
are either move assigned to or destroyed.
Ensures: a
shall be equal to the value that rv
had before this
assignment.
其中 a
是目的地,rv
是右值。这 可以 通过交换 1 与源目的地的元素来实现,但最有可能通过调整大小然后移动来完成。
- 它必须通过非专业化
__swap
,以确保移动分配确实发生。
来自 another question (actually, rather this one,但前者是更好的参考),除了 20.5.5.15:
,我在标准中找不到合适的参考Objects of types defined in the C++ standard library may be moved from (15.8). Move operations may be explicitly specified or implicitly generated. Unless otherwise specified, such moved-from objects shall be placed in a valid but unspecified state.
对目标容器中先前包含的元素是否有任何要求,例如。 G。在分配前被销毁?
示例:
std::list<SomeClass> v1({10, 12});
std::list<SomeClass> v2({7});
v1 = std::move(v2);
for(auto sc : v2)
{
std::cout << sc << ' ';
}
虽然 GCC 根本没有输出任何东西(std::vector
和 std::list
类似),但会收到 10 12
作为输出合法(适当的 operator<<
提供)(例如通过交换内容接收,特别是不删除以前包含的对象)?
截至目前,我会说 "yes",但感觉不够确定可以依赖并且太好奇而不 post 一个问题...
如果合法,如果不立即销毁元素(例如,结果某些资源仍然保持打开状态,而开发人员希望它们关闭),任何开发人员都会出乎意料吗?
在[container.requirements.general]
中,我们看到
All existing elements of
a
are either move assigned to or destroyed. Ensures:a
shall be equal to the value thatrv
had before this assignment.
其中 a
是目的地,rv
是右值。这 可以 通过交换 1 与源目的地的元素来实现,但最有可能通过调整大小然后移动来完成。
- 它必须通过非专业化
__swap
,以确保移动分配确实发生。