【发布时间】:2014-11-04 16:46:00
【问题描述】:
我对向量 push_back 的行为方式有点困惑,对于下面的 sn-p,我希望复制构造函数只被调用两次,但输出表明并非如此。是否是向量内部重组导致了这种行为。
输出:
Inside default Inside copy with my_int = 0 Inside copy with my_int = 0 Inside copy with my_int = 1
class Myint
{
private:
int my_int;
public:
Myint() : my_int(0)
{
cout << "Inside default " << endl;
}
Myint(const Myint& x) : my_int(x.my_int)
{
cout << "Inside copy with my_int = " << x.my_int << endl;
}
void set(const int &x)
{
my_int = x;
}
}
vector<Myint> myints;
Myint x;
myints.push_back(x);
x.set(1);
myints.push_back(x);
【问题讨论】:
-
与
emplace_back相关的问题:stackoverflow.com/questions/23948442/… -
取决于对象,如果你另外定义一个移动构造函数,它将移动而不是复制,这样更有效。另见c++ - How to enforce move semantics when a vector grows? - Stack Overflow