FAQ 22.11 Are there exceptions to the rule Initialize all member objects in an initialization list ?

FAQ 22.11 Are there exceptions to the rule "Initialize all member objects in an initialization list"?

graphics/new_icon.gif

Yes, to facilitate argument screening.

Arguments to constructors sometimes need to be checked (or screened) before they can be used to initialize a member object. When it becomes difficult to squeeze the resultant if (...) throw ... logic into the initialization list, it may be more convenient to initialize the member object via its default constructor, then modify its state in the constructor body ({...}) via assignment or some other mutative member function.

This situation is usually limited to classes that are built directly on built-in types (int, char*, and so forth), because constructors for user-defined (class) types normally check their own arguments.

For example, in the preceding FAQ, MyString::MyString(const char*) passed its parameter to strlen(const char*) without verifying that the pointer was non-NULL. This test can be implemented by using assignment in the constructor.

 #include <new> #include <cstdlib> #include <stdexcept> using namespace std; class MyString { public:   MyString(const char* s) throw(bad_alloc, runtime_error);   MyString(const MyString& s) throw(bad_alloc);   MyString& operator= (const MyString& s) throw(bad_alloc);  ~MyString() throw(); protected:   unsigned len_;   char*    data_; }; MyString::MyString(const char* s) throw(bad_alloc, runtime_error) // No initialization list due to argument screening {   if (s == NULL)     throw runtime_error("NULL pointer in MyString ctor");   len_ = strlen(s);   data_ = new char[len_+1];   memcpy(data_, s, len_+1); } MyString::~MyString() throw() { delete[] data_; } int main() { MyString s = "xyzzy"; } 

Using assignment rather than initialization tends to remove order dependencies. For example, MyString::MyString(const char*) no longer introduces an order dependency in the member data of class MyString. However, doing this may introduce performance penalties if the member objects are user-defined (class) types.



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