【发布时间】:2013-03-21 19:01:07
【问题描述】:
给定类X 下面(明确定义的以外的特殊成员函数与本实验无关):
struct X
{
X() { }
X(int) { }
X(X const&) { std::cout << "X(X const&)" << std::endl; }
X(X&&) { std::cout << "X(X&&)" << std::endl; }
};
以下程序创建X 类型的对象向量并调整其大小,使其超出容量并强制重新分配:
#include <iostream>
#include <vector>
int main()
{
std::vector<X> v(5);
v.resize(v.capacity() + 1);
}
由于X 类提供了移动构造函数,我希望向量的先前内容在重新分配后移动 到新存储中。令人惊讶的是,that does not seem to be the case,我得到的输出是:
X(X const&)
X(X const&)
X(X const&)
X(X const&)
X(X const&)
为什么?
【问题讨论】:
-
另请注意,Microsoft 不遵守此规则,因此此代码使用 Visual C++(或 clang Windows) 将调用移动构造函数,因此在调整大小失败的情况下,
std::vector中的元素可能会损坏(空)。
标签: c++ c++11 copy-constructor move-semantics