FAQ 22.09 Is it moral for one member object to be initialized using another member object in the constructor s initialization list?

FAQ 22.09 Is it moral for one member object to be initialized using another member object in the constructor's initialization list?

Yes, but exercise great caution.

In a constructor's initialization list, it is best to avoid using one member object from the this object in the initialization expression of a subsequent initializer for the this object. This guideline prevents subtle order dependency errors if someone reorganizes the layout of member objects within the class (see the previous FAQ).

Because of this guideline, the constructor that follows uses s.len_ + 1 rather than len_ + 1, even though they are otherwise equivalent. This avoids an unnecessary order dependency.

 #include <new> using namespace std; class MyString { public:   MyString()                              throw(bad_alloc);  ~MyString()                              throw();   MyString(const MyString& s)             throw(bad_alloc);                                           // Copy constructor   MyString& operator= (const MyString& s) throw(bad_alloc);                                           // Assignment protected:   unsigned len_;   char*    data_; }; MyString::MyString() throw(bad_alloc) : len_(0) , data_(new char[1]) { data_[0] = '\0'; } MyString::~MyString() throw() { delete[] data_; } MyString::MyString(const MyString& s) throw(bad_alloc) : len_ ( s.len_             ) , data_( new char[s.len_+1] )                        <-- 1 { memcpy(data_, s.data_, len_+1); } int main() {   MyString a;      // Default ctor; zero length String ("")   MyString b = a;  // Copy constructor } 

(1) Not new char[len_+1]

An unnecessary order dependency on the class layout of len_ and data_ would have been introduced if the constructor's initialization of data_ had used len_+1 rather than s.len_+1. However using len_ within a constructor body ({...}) is okay. No order dependency is introduced since the entire initialization list is guaranteed to finish before the constructor body begins executing.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net