-
Notifications
You must be signed in to change notification settings - Fork 411
Open
Description
CPP/week11/examples/example2/mystring.hpp
Lines 29 to 48 in 8d45044
| MyString & operator=(const MyString &ms) | |
| { | |
| create(ms.buf_len, ms.characters); | |
| return *this; | |
| } | |
| bool create(int buf_len, const char * data) | |
| { | |
| release(); | |
| this->buf_len = buf_len; | |
| if( this->buf_len != 0) | |
| { | |
| this->characters = new char[this->buf_len]{}; | |
| } | |
| if(data) | |
| strncpy(this->characters, data, this->buf_len); | |
| return true; | |
| } |
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:
MyString& operator=(const MyString& ms)
{
if (this != &ms)
{
create(ms.buf_len, ms.characters);
}
return *this;
}Issue2: not exception safe
In create function, if new 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:
bool create(int buf_len, const char* data)
{
char* new_characters = NULL;
if (buf_len != 0)
{
new_characters = new char[buf_len] {};
}
if ((new_characters != NULL) && (data != NULL))
strncpy(new_characters, data, buf_len);
release();
this->buf_len = buf_len;
this->characters = new_characters;
return true;
}See also
- C++ Primer (5th Edition) Section 13.2 Copy Control and Resource Management
- C.62: Make copy assignment safe for self-assignment - C++ Core Guidelines
- C.65: Make move assignment safe for self-assignment - C++ Core Guidelines
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels