gpt4 book ai didi

c++ - 复制构造函数优于移动构造函数?

转载 作者:行者123 更新时间:2023-11-30 03:22:08 25 4
gpt4 key购买 nike

<分区>

为了好玩,我正在开发一个简单的 JSON 解析器,并且我有我的值类型:

typedef enum {
JSON_NULL,
JSON_NUMBER,
JSON_STRING,
JSON_ARRAY,
JSON_OBJECT,
JSON_BOOLEAN
} json_type_t;

// datatype for json value
struct json_value {
using arr_type = vector<json_value>;
using obj_pair = pair<string, json_value>;
using obj_type = unordered_map<string, json_value>;

// constructors
json_value()
: type(JSON_NULL) {}

json_value(json_type_t type)
: type(type) {
switch(type) {
case JSON_STRING: str = new string; break;
case JSON_ARRAY: arr = new arr_type; break;
case JSON_OBJECT: obj = new obj_type; break;
default:
break;
}
}

// copy construct
json_value(const json_value& other) {
printf("copying json value\n");
if (other.type != JSON_NULL) {
type = other.type;
switch(type) {
case JSON_NULL: return;
case JSON_NUMBER: num = other.num; return;
case JSON_BOOLEAN: val = other.val; return;
case JSON_STRING: str = new string (*other.str); return;
case JSON_ARRAY: arr = new arr_type(*other.arr); return;
case JSON_OBJECT: obj = new obj_type(*other.obj); return;
}
}
}

// move construct
json_value(json_value&& other) {
type = other.type;
switch(type) {
case JSON_NULL: break;
case JSON_NUMBER: num = other.num; break;
case JSON_BOOLEAN: val = other.val; break;
case JSON_STRING: str = other.str; other.str = nullptr; break;
case JSON_ARRAY: arr = other.arr; other.arr = nullptr; break;
case JSON_OBJECT: obj = other.obj; other.obj = nullptr; break;
}
}

// assignment operator copy/swap idiom
json_value& operator =(json_value other) {
destroy();
type = other.type;
switch(type) {
case JSON_NULL: break;
case JSON_NUMBER: num = other.num; break;
case JSON_BOOLEAN: val = other.val; break;
case JSON_STRING: str = other.str; other.str = nullptr; break;
case JSON_ARRAY: arr = other.arr; other.arr = nullptr; break;
case JSON_OBJECT: obj = other.obj; other.obj = nullptr; break;
}
return *this;
}

// destructor
~json_value() {
destroy();
}

// type of value and union to hold data
json_type_t type = JSON_NULL;
union {
bool val;
double num;
string *str;
arr_type *arr;
obj_type *obj;
};

private:
// cleanup our memory
void destroy() {
switch(type) {
case JSON_NULL: break;
case JSON_NUMBER: break;
case JSON_BOOLEAN: break;
case JSON_STRING: delete str; break;
case JSON_ARRAY: delete arr; break;
case JSON_OBJECT: delete obj; break;
}
type = JSON_NULL;
}
};

我已经编写了适当的复制/移动构造函数和赋值运算符。我的问题是,在运行特定基准测试时,解析器需要大约 40 毫秒。为了稍微优化一下,我注释掉了复制构造函数以确保我没有制作任何不必要的拷贝。果然,我的代码仍然可以编译,表明移动构造函数足够了,而且它快了 ~25%!

检测复制构造函数,我可以看到它确实被调用了,但正如我所展示的,移动构造函数就足够了。

所以,我的问题是,在什么情况下复制构造函数比移动构造函数更受欢迎,我如何找到发生这种情况的位置?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com