我可以调整从中移出的矢量的大小吗?

Can I resize a vector that was moved from?

我有一些代码,我想在其中绝对确保移出 std::vector 不会留下秘密数据(考虑加密密钥管理)。在我的 class' 移动构造函数中,我做了类似的事情:

X(X&& rhs): secret_vector{std::move(rhs.secret_vector)}{
    rhs.secret_vector.resize(N);
    safe_zero(rhs.secret_vector); // zero out all elements
    rhs.secret_vector.resize(0);
}

如您所见,我在移动后重新使用了秘密向量。我看了

Reusing a moved container?

但我不是很清楚我能做到这一点(我不明白 "pre-conditions" 到底是什么)。

我的问题是:我可以调整移动自 std::vector 的大小,对其执行一些操作,然后将其调整回零吗?

[defns.valid] valid but unspecified state value of an object that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type

[Example: If an object x of type std::vector is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. — end example]

std::vector::resize 没有任何先决条件。无论向量处于什么有效状态,调整它的大小都不会有未定义的行为(忽略由包含元素的构造函数引起的 UB;但当参数为 0 时不会调用这些)。

My question is: can I resize a moved-from std::vector, perform some operation on it, then resize it back to zero?

从对象中移出的对象应处于未指定但有效的状态。

因此您有权调整它的大小(不需要先决条件)。 safe_zero它,清除它。

(I did not understand what "pre-conditions" really are).

存在对象不调用 UB 的状态条件。

例如,operator[](std::size_t i) 要求 i < size().

resize(),clear()没有要求。

是的。如链接问题中所述,该对象处于有效但未指定的状态。这意味着您不能对 std::vector 的内容做出任何假设。调用 size 是安全的,但它可能 return 与移动前的值不同。向量的状态是有效的,这意味着内部没有悬挂指针或任何东西,包括 resize 在内的所有成员函数都可以正常工作。此外,调用 resize 是少数几个有意义的函数之一,因为它 "respecifies" 向量的状态。