I am trying to understand the correct way to implement the copy-assignment operator =
. So I've implemented this example:
class Window {
public:
Window(const std::string& = std::string());
Window(const Window&);
Window& operator=(const Window&);
~Window();
std::string win_name()const { return *psWinName; }
std::size_t win_id()const { return winID; }
private:
std::string* psWinName = nullptr;
std::size_t winID;
};
Window::Window(const std::string& win_name) :
psWinName(new std::string(win_name)),
winID(0) {
}
Window::Window(const Window& rhs) :
psWinName(new std::string(*rhs.psWinName)),
winID(rhs.winID) {
}
/* Erroneous copy-assignment operator
Window& Window::operator=(const Window& rhs)
{
delete psWinName;
psWinName = new std::string(*rhs.psWinName);;
winID = rhs.winID;
return *this;
}
*/
Window& Window::operator=(const Window& rhs)
{
std::string* tmp = new std::string(*rhs.psWinName);
delete psWinName;
psWinName = tmp;
winID = rhs.winID;
return *this;
}
Window::~Window()
{
delete psWinName;
}
int main()
{
/*Window win_explorer("Explorer");
auto win_exp2(win_explorer);
Window win_desktop("Desktop Window");
Window win;
win = win_desktop;
win = win;
cout << win_explorer.win_name() << " : " << win_explorer.win_id() << endl;
cout << win_exp2.win_name() << " : " << win_exp2.win_id() << endl;
cout << win_desktop.win_name() << " : " << win_desktop.win_id() << endl;
cout << win.win_name() << " : " << win.win_id() << endl;*/
int* p = new int(9);
cout << p << " " << *p << endl;
int* tmp = p;
cout << tmp << " " << *tmp << endl;
delete p;
p = new int(*tmp);
cout << p << " " << *p << endl;
cout << tmp << " " << *tmp << endl;
cout << "\ndone\n";
}
So as far I've showed the incorrect form of =
operator.
Is it wrong because:
delete psName;
psName = new std::string(*rhs.psName); // UB here?
So I don't know how the Order of evaluation occurs here:
psName = new std::string(*rhs.psName);
. So is this a UB?Also what about:
delete psName; psName = new std::string(); *psName = *rhs.psName;
But yields the same result which is undefined value.
- I talk bout assigning some object to itself.
** Also people argue about: delete psName; psName = new std::string();
they say new
may throw. But I think it shouldn't as long as I've released a resource the same as it has.
** N.B: In fact I am not about a std::string
but about any resource to acquire.