vector 中的匿名构造函数和析构函数调用
Anonymous constructor and destructor call in vector
我对下面的程序及其输出有点困惑。
有人可以澄清一下吗?
#include <iostream>
#include <vector>
using namespace std;
class sample
{
public:
int a;
sample( ){ cout<<" Am in Default Cons "<< a << "\n"; }
sample( int b ){ a=b; cout<<" Am in Cons "<< a << "\n"; }
sample(const sample& s){ a=s.a; cout<<" Am in copy " <<s.a<<"\n"; }
~sample(){ cout<<" Am in Des "<<a <<"\n"; }
};
int main()
{
vector < sample > Object;
{
Object.push_back( sample( 1 ));
Object.push_back( sample( 2 ));
cout<<" End of loop \n";
}
cout<<" \n End of Program \n";
return 0;
}
输出为
Am in Cons 1 // Understood this is for object 1 creation
Am in copy 1 // Understood this is for object 1 copy to vector
Am in Des 1 // Understood this is for object 1 destruction.
Am in Cons 2 // Understood this is for object 2 creation
Am in copy 2 // Understood this is for object 2 copy to vector
Am in copy 1 // **Don't understand this COPY CALL**
Am in Des 1 // **Don't understand this DESTRUCTOR CALL**
Am in Des 2 // Understood this is for object 2 destruction.
End of loop
End of Program
Am in Des 1 //// Understood this is for object 1 destruction in vector .
Am in Des 2 //// Understood this is for object 2 destruction in vector .
std::vector
是一个动态数组。当您添加一个元素并且其内部缓冲区的容量已满时,vector
需要:
- 分配新的内存缓冲区,
- copy/move 个元素从旧缓冲区到新缓冲区,
- 销毁原始缓冲区中的元素,
- 取消分配原始缓冲区,
- copy/move 在新缓冲区的末尾添加了元素。
(不一定是这个顺序。)
Step 2.涉及到你不懂的copy constructor。第3步涉及你不懂的析构函数
为防止这种(低效的)行为,请在插入元素之前使用 std::vector::reserve
(如果可以的话)。然后不会重新分配,也不会隐藏 copy/move 元素。
我对下面的程序及其输出有点困惑。
有人可以澄清一下吗?
#include <iostream>
#include <vector>
using namespace std;
class sample
{
public:
int a;
sample( ){ cout<<" Am in Default Cons "<< a << "\n"; }
sample( int b ){ a=b; cout<<" Am in Cons "<< a << "\n"; }
sample(const sample& s){ a=s.a; cout<<" Am in copy " <<s.a<<"\n"; }
~sample(){ cout<<" Am in Des "<<a <<"\n"; }
};
int main()
{
vector < sample > Object;
{
Object.push_back( sample( 1 ));
Object.push_back( sample( 2 ));
cout<<" End of loop \n";
}
cout<<" \n End of Program \n";
return 0;
}
输出为
Am in Cons 1 // Understood this is for object 1 creation Am in copy 1 // Understood this is for object 1 copy to vector Am in Des 1 // Understood this is for object 1 destruction. Am in Cons 2 // Understood this is for object 2 creation Am in copy 2 // Understood this is for object 2 copy to vector Am in copy 1 // **Don't understand this COPY CALL** Am in Des 1 // **Don't understand this DESTRUCTOR CALL** Am in Des 2 // Understood this is for object 2 destruction. End of loop End of Program Am in Des 1 //// Understood this is for object 1 destruction in vector . Am in Des 2 //// Understood this is for object 2 destruction in vector .
std::vector
是一个动态数组。当您添加一个元素并且其内部缓冲区的容量已满时,vector
需要:
- 分配新的内存缓冲区,
- copy/move 个元素从旧缓冲区到新缓冲区,
- 销毁原始缓冲区中的元素,
- 取消分配原始缓冲区,
- copy/move 在新缓冲区的末尾添加了元素。
(不一定是这个顺序。)
Step 2.涉及到你不懂的copy constructor。第3步涉及你不懂的析构函数
为防止这种(低效的)行为,请在插入元素之前使用 std::vector::reserve
(如果可以的话)。然后不会重新分配,也不会隐藏 copy/move 元素。