gpt4 book ai didi

c++ - std::vector::push_back 是否有前置条件?

转载 作者:行者123 更新时间:2023-11-30 01:24:04 26 4
gpt4 key购买 nike

comments on Andrzej's move constructor article ,我发布了一个 moved from object 可以调用任何没有前置条件的成员函数。我给出了示例 std::vector::front 作为一个函数,你不能在移动的 std::vector 上调用它,因为它有一个前提条件 vector 不为空。我给出了 std::vector::emptystd::vector::push_backstd::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 ]

最佳答案

What is the context of move constructors leaving an object in a valid but unspecified state, and does it apply to potential out-of-memory situations with std::vector::push_back?

不,它不适用。有足够的内存来执行 push_back 不是先决条件。当系统没有更多内存时调用 push_back 是可以的(通常程序不可能提前知道分配是否成功)并且如果没有足够的内存你得到一个异常(exception)。这只是 push_back 的正常行为,而不是违反前提条件。

In particular, if std::vector::push_back would have worked prior to a move, is it guaranteed to work after (ignoring issues such as other processes using up memory)?

尝试 push_back 是合法的,但不能保证一定有效。移动之后, vector 的存储可能已移动到移动目标,push_back 可能导致重新分配,这可能会失败并抛出 bad_alloc

但是忽略分配失败,push_back 将会成功,正如 Howard 的评论所说,现在您的 vector 之前有一个未知数量的元素,现在有一个未知数量加一。有效但不是很有用。

关于c++ - std::vector::push_back 是否有前置条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com