I'm currently writing an own string implementation in C++. (Just for exercise).
However, I currently have this copy-constructor:
// "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;
}
and I wanted to increase performance a little bit. So I came on the idea using memcpy()
to just copy obj
into *this
.
Just like that:
// "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>));
}
Is it safe to overwrite the data of *this
like that? Or may this produce any problems?
Thanks in advance!