本文发表在 rolia.net 枫下论坛But I noticed that it's used quite often to implement other methods in STL.
Think about this, you have a vector like this
template < typename T>
class vector {
T* start, *finish, *end_of_storage;
T& operator=(const T& rhs);
... ...
}
How do you implement operator=?, don't forget exception safety here.
When you call operator=, the caller object has been constructed before that, i.e. "this" pointer is fixed, can't be changed, right?
Can you destroy objects in the caller vector first, then copy construct every object from the vector rhs? No, think about it. What if one of the constructor calls fails?
swap() can be handy in this situation.
You can create a local object within operator=(), say C, and call swap() to swap the member variables : pointers, of C and *this, when operator= returns, C will be cleared automically as well as the objects inside C
Sorry, I can't post on this issue anymore. Lots of other things to do.
Anyway I recommend you to read exceptional C++ and more exceptional C++, they have some in-depth analysis about swap() function. Very intersting books, but too difficult to me at times. We can discuss this in PM if you want, I'm a C/C++, Unix programmer coming from C. I like to learn together and improve together with buddies. Thanks for posting your thoughts, it's always a good thing to hear other people's opinions.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Think about this, you have a vector like this
template < typename T>
class vector {
T* start, *finish, *end_of_storage;
T& operator=(const T& rhs);
... ...
}
How do you implement operator=?, don't forget exception safety here.
When you call operator=, the caller object has been constructed before that, i.e. "this" pointer is fixed, can't be changed, right?
Can you destroy objects in the caller vector first, then copy construct every object from the vector rhs? No, think about it. What if one of the constructor calls fails?
swap() can be handy in this situation.
You can create a local object within operator=(), say C, and call swap() to swap the member variables : pointers, of C and *this, when operator= returns, C will be cleared automically as well as the objects inside C
Sorry, I can't post on this issue anymore. Lots of other things to do.
Anyway I recommend you to read exceptional C++ and more exceptional C++, they have some in-depth analysis about swap() function. Very intersting books, but too difficult to me at times. We can discuss this in PM if you want, I'm a C/C++, Unix programmer coming from C. I like to learn together and improve together with buddies. Thanks for posting your thoughts, it's always a good thing to hear other people's opinions.更多精彩文章及讨论,请光临枫下论坛 rolia.net