Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Uniform and Convenient Initialization Syntax-2 : Page 2


advertisement
Against All PODs
An aggregate is:
  • A POD struct, class, or unions
  • An array of a POD type
The initializer of an aggregate looks like this:

struct Point1{ int x; int y; //... }; Point1 p1 = {1,2}; //aggregate initialization

However, when you deal with a class that has a constructor, you must use a different initialization form:

class Point2 { public: Point2( int x, int y ); // ... }; Point2 p2(1,0);

This diversity makes the design of generic code difficult because a template that initializes an arbitrary object must know whether the object is an aggregate or a class with a constructor.



Things get messier when you use container objects. Take for example a vector of strings. Today, you have to "initialize" such a container by hand:

vector<string> vs; vs.push_back("ab"); vs.push_back( "cd"); vs.push_back("ef");

Alternatively, you can create an array of strings and use it to initialize the container:

string arr[] = {"ab", "cd", "ef"}; // initialize the container with an existing array vector vs( arr, arr+3);

This is highly inefficient, error-prone, and pretty disgusting.

Initialization Loopholes
Agreed, C++98 initialization is messy. In addition, it has two known loopholes. You have no means of initializing arrays that are data members nor can you initialize dynamically-allocated arrays of POD types. As a workaround, programmers assign a value to each element manually:

//member array class C { int arr[3]; public: C() { arr[0]=1; arr[1]=2; arr[2]=3; } }; //dynamically allocated array int* p = new int[3]; p[0]=1; p[1]=2; p[2]=3;

Imagine if you had to "initialize" an array with thousands of elements in this way! This is not to mention the risk of accidentally skipping elements or initializing elements that don't exist. Fortunately, C++0x has a much better solution.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap