我的代码如下:
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
struct X
{
X() { cout << "X()" << endl; }
X( const string &s ):item( s ) { cout << "X( initialize by str(" << s << ") )" << endl; }
X( const& X ) { cout << "X( const X& )" << endl; }
~X() { cout << "X(" << (*this).item << ") was destroy" << endl; }
string item;
};
int main()
{
X a( "aa" );
X b( "bb" );
X c( "cc" );
vector<X> vec;
vec.push_back( a );
vec.push_back( b );
vec.push_back( c );
vec[0].item = "vec_aa";
vec[1].item = "vec_bb";
vec[2].item = "vec_cc";
}当我运行这个程序时,我得到了这个输出:
X(由str(aa)初始化)
X(由str(bb)初始化)
X(由str(cc)初始化)
X(aa)被摧毁
X(aa)被摧毁
X(bb)被摧毁
X(vec_aa)被摧毁
X(vec_bb)被摧毁
X(vec_cc)被摧毁
X(cc)被摧毁
X(bb)被摧毁
X(aa)被摧毁
所以,我的问题是:它为什么输出
X(aa) was destroy
X(aa) was destroy
X(bb) was destroy 我预期输出是
X(aa) was destroy
X(bb) was destroy
X(cc) was destroy 发布于 2021-12-08 09:05:45
std::vector驻留在连续内存中--如果还不够大,就需要重新调整大小,这意味着在新内存中分配新内存、移动(如果可用)或复制构造新内存中的对象,并在删除之前销毁旧内存中的对象。
显然,这样的重新分配会发生两次,这就是您意外的输出的来源:
X(aa) was destroy // first re-allocation: copy of aa resides in vector with
// capacity of size 1, but needs to be 2
X(aa) was destroy // second re-allocation: copies of aa and bb reside in
X(bb) was destroy // vector with capacity of 2, but needs to be 3
// (will, most likely, actually get 4)您可以避免这一点,如果您预先reserve足够的内存-这是您应该做的,如果您事先知道(即使只是粗略地)有多少对象,您将放置到向量中,因为重新分配是昂贵的。
https://stackoverflow.com/questions/70272092
复制相似问题