-
Notifications
You must be signed in to change notification settings - Fork 352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MyString's copy assignment operator can't handle self-assignment correctly and not exception safe #30
Comments
The second issue is related to exception safety. In the create() function, if the memory allocation for new char[buf_len] throws an exception, the original state of the object (*this) may already be altered, leading to an invalid or inconsistent state (like leaked memory). This breaks the "basic exception safety guarantee," which requires that an object remain in a valid state if an exception is thrown. Solution: Copy-and-Swap Idiom for Exception Safety Here’s how the MyString class can be improved: Improved MyString Class class MyString { public:
}; |
Issue 1: Self-Assignment |
CPP/week11/examples/example2/mystring.hpp
Lines 29 to 48 in 8d45044
Issue1: can't handle self-assignment
See: Assignment Operators, C++ FAQ (isocpp.org)
If
x = x
, bad errors will occur.We can handle self-assignment by explicitly testing for self-assignment:
Issue2: not exception safe
In
create
function, ifnew char[this->buf_len]{};
throws an exception,*this
won't keep a valid state. So, copy assignment operator is not exception safe.The solution is copy the underlying data firstly, then delete
*this
's old resource:See also
The text was updated successfully, but these errors were encountered: