I have a class with pointer to char. I am wondering how is it possible that copy construction is possible without explicitly defining copy constructor?
I assume because the object was already allocated, but if so, then why would someone need copy constructors in the first place?
#include <iostream>
#include <cstring>
class Data {
public:
explicit Data(const char* newData)
:size{strlen(newData)},
data{size ? new char[size] : nullptr}
{
std::memcpy(data, newData, size);
}
friend std::ostream& operator<<(std::ostream& ost, const Data& rhs) {
for (std::size_t i = 0; i < rhs.size; i++) {
std::cout << rhs.data[i];
}
ost << "\n";
return ost;
}
~Data() {
delete[] data;
}
private:
std::size_t size;
char* data;
};
int main() {
Data data1{"data1"};
Data data2{data1}; // copy constructor
std::cout << data1;
std::cout << data2;
return 0;
}
Output:
data1
data1
Shouldn't the copy constructor look like that? I am often seeing such examples. But since the default constructor already did that, then when do I actually need to define copy ctor?
Data(const Data& other) {
if (this != &other) {
size = other.size;
data = new char[size];
std::memcpy(data, other.data, size);
}
}
By the way, I realize the code introduces some maul practices (e.g. using new instead of smart ptrs, not using string in the first place, etc. - but it's just an exercise).