I have a Person class in which I use the Pimpl idom for its structure:
Person.h
#include <memory>
class Person {
public:
Person();
Person(std::string name, double val);
Person (const Person& src);
Person&operator=(const Person& src);
~Person();
struct Impl;
std::unique_ptr<Impl> pImpl;
};
Person.cpp
#include "person.h"
#include <memory>
#include <string>
struct Person::Impl {
Impl(std::string _name, double d) : name(std::move(_name)), age(d) {}
std::string name;
double age;
};
Person::Person(std::string name, double val) : pImpl(std::make_unique<Impl>(std::move(name), val)) {}
Person::Person(const Person &src) {
this->pImpl = std::make_unique<Impl>(*src.pImpl);
}
Person::Person() : pImpl(std::make_unique<Impl>("", 0)) {}
Person::~Person() = default;
So my question is about the coppy assignement operator :
I wrote 2 versions below (ver1) and (ver2) :
ver1:
Person &Person::operator=(const Person &src) {
*pImpl = *src.pImpl;
return *this;
}
ver2
Person &Person::operator=(const Person &src) {
pImpl = std::make_unique<Impl>(*src.pImpl);
return *this;
}
main
int main() {
Person w1("Aymen", 38);
Person w2;
w2 = w1;
return 0;
}
So both of them works as expected , w2 has its own data and w1 too. I was wondering that using ver1 as I am doing assignement between 2 pointers, they both will point to the same thing so when I thought that when I will change data on w1 it will change w2 too, but was not the case.
My question is why in the ver1 it is not a shallow copy or may be I did it wrong in the first place.
Thank you.
Aucun commentaire:
Enregistrer un commentaire