【发布时间】:2018-11-27 04:04:50
【问题描述】:
我目前正在用 C++ 编写自己的字符串实现。 (只是为了锻炼)。
但是,我目前有这个复制构造函数:
// "obj" has the same type of *this, it's just another string object
string_base<T>(const string_base<T> &obj)
: len(obj.length()), cap(obj.capacity()) {
raw_data = new T[cap];
for (unsigned i = 0; i < cap; i++)
raw_data[i] = obj.data()[i];
raw_data[len] = 0x00;
}
我想稍微提高性能。所以我想到了使用memcpy() 将obj 复制到*this 的想法。
就这样:
// "obj" has the same type of *this, it's just another string object
string_base<T>(const string_base<T> &obj) {
memcpy(this, &obj, sizeof(string_base<T>));
}
这样覆盖*this的数据安全吗?或者这会产生什么问题?
提前致谢!
【问题讨论】:
-
这个帖子读起来很有趣;几乎重复:stackoverflow.com/questions/30114397/…
-
你也可以使用在 NULL 字符处停止的 strcpy。与 memcpy 相比,它可能在性能方面有所不同
-
要考虑的另一件事是,现代编译器通常足够聪明,可以识别第一个示例中的循环,并在适当的时候将其替换为 memcpy。所以这可能是一个过早的优化。
-
顺便说一句,您只需要复制
len对象,而不是cap。
标签: c++ arrays memcpy this-pointer