Previously I had understood a little about deep copy (basic data types), then I tried to make an exercise with std::string, for copy constructor it worked, but for operator = I'm still a bit confused,
#include <iostream>
class Person {
//heap
std::string *m_name;
public:
Person(std::string_view name) : m_name {new std::string(name)} {
std::cout << "Constructing..." << m_name << " ("<< *m_name << ") " << std::endl;
}
//deep copy
Person(const Person &p){
std::cout << "deep copy..." << std::endl;
m_name = new std::string(*p.m_name);
}
Person& operator=(const Person& p) {
if (&p == this) return *this;
//everything I comment means it doesn't work
// m_name = p.m_name;
// m_name = new std::string(*p.m_name);
// *m_name = *p.m_name;
// m_name = new std::string(*p.m_name);
// *m_name = *p.m_name;
// size_t length = p.m_name->size();
// m_name = new std::string[length];
// *m_name = *p.m_name;
// size_t length = m_name->size();
// m_name = new std::string[length];
// for(size_t i {0}; i<length; ++i){
// m_name[i] = p.m_name[i];
// }
return *this;
}
//deep copy
~Person() {
std::cout << "Destructing..." << m_name << " (" << *m_name << ") " << std::endl;
delete m_name;
}
};
void caller() {
Person rudy {"rudy"};
Person rusty = rudy;
}
int main(int argc, char const **argv) {
std::cout << "Calling caller()" << std::endl;
caller();
std::cout << "Back in main()" << std::endl;
return 0;
}
it seems easy if you use a basic type like int how does the copy constructor work but operator = doesn't work?