为了更好地理解副本构造函数和移动构造函数,我编写了一个源代码,其中清楚记录了构造函数/析构函数的每次调用。
通过将向量中我类的两个不同对象推入向量,我意识到第一个对象被破坏,然后被一个新的对象替换(调用复制构造函数)。如何避免这种情况?
这是我的代码:
req.body._device_id
以下是输出:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#define title(args) std::cout << "------ " << args << " ------" << std::endl
//******************** struct X
struct X
{
// Count objects having the same name:
static std::map<std::string, int> counter;
// For logging and for the counter:
std::string name;
int id;
// Some data to be allocated:
long *data;
//******************** X(const std::string &s)
X(const std::string &s) : name(s)
{
init();
log("Constructor");
}
//******************** X(const X &x)
X(const X &x) : name(x.name)
{
init();
log("Copy constructor");
}
//******************** X(X &&x)
X(X &&x) : name(x.name)
{
init();
x.data = nullptr;
log("Move constructor");
}
//******************** void init()
void init()
{
data = new long();
id = ++X::counter[name];
}
//******************** ~X()
~X()
{
log("Destructor");
if (data != nullptr) {
free(data);
}
}
//******************** void log(const std::string &message="") const
void log(const std::string &message="") const
{
std::cout << " " << name << "-" << id << " " << message << std::endl;
}
};
std::map<std::string, int> X::counter;
//******************** main ()
int main ()
{
std::vector<X> v;
title("Construction foobar");
v.push_back(X("foo"));
title("Construction superman");
v.push_back(X("superman"));
title("Show the vector");
for (auto &x : v) {
x.log();
}
title("Bye");
return 0;
}
我不明白为什么------ Construction foobar ------
foo-1 Constructor
foo-2 Move constructor
foo-1 Destructor
------ Construction superman ------
superman-1 Constructor
superman-2 Move constructor
foo-3 Copy constructor <== How can I avoid this ?
foo-2 Destructor <==
superman-1 Destructor
------ Show the vector ------
foo-3
superman-2
------ Bye ------
foo-3 Destructor
superman-2 Destructor
被销毁而创建了foo-2
。
这就是我所期望的:
foo-3