我目前正在用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
的数据是安全的吗?或者会产生任何问题吗?
提前感谢!