【发布时间】:2013-01-05 04:53:00
【问题描述】:
在comments on Andrzej's move constructor article 中,我发布了一个已移动的对象可以调用任何没有前置条件的成员函数。我给出了示例 std::vector::front 作为一个函数,您不能在已移动的 std::vector 上调用该函数,因为它具有向量不为空的前提条件。我给出了std::vector::empty、std::vector::push_back 和std::vector::reserve 的示例,作为您可以(但不应该)调用从std::vector 移出的函数,因为它们没有前置条件。
然而,这让我开始思考。 std::vector::push_back 要求主机系统上有足够的连续内存可用。这对于 std::vector 对象来说并不是一个要求,因为它是关于它正在运行的系统,但在我看来这仍然是一个先决条件。
移动构造函数使对象处于有效但未指定状态的上下文是什么,它是否适用于std::vector::push_back 的潜在内存不足情况?特别是,如果std::vector::push_back 在移动之前可以工作,那么它是否保证在之后也可以工作(忽略其他进程耗尽内存等问题)?
供参考:§ 17.6.3.1
Table 20 — MoveConstructible requirements [moveconstructible]
Expression Post-condition
T u = rv; u is equivalent to the value of rv before the construction
T(rv) T(rv) is equivalent to the value of rv before the construction
rv’s state is unspecified [ Note:rv must still meet the requirements of the library compo-
nent that is using it. The operations listed in those requirements must work as specified
whether rv has been moved from or not. — end note ]
【问题讨论】:
-
从
vector移出的push_back是合法的,但毫无意义。vector在push_back之前和之后都处于有效但未指定的状态,除非如果成功,您现在知道最后一个元素是什么。 -
我完全同意你的观点(我在博客上的帖子中强调了一点),我只是从严格的语言角度想知道。
标签: c++ c++11 language-lawyer move-constructor preconditions