当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - C++11 universal initialization cause unexpected initialization?

问题描述:

In C++ 11, The new universal initialization syntax can also be used to call a normal constructor (that doesn't take a initializer_list parameter). While by looking it is not bad, I think that could cause a problem in real world usage.

So suppose in my project I use a library that comes with the following class:

class Foo

{

public:

Foo(int size, int value); // create 'size' number of elements

Foo(initializer_list<int> list); // create elements as in 'list'

}

In the project it is used in this way:

Foo foo{10, 2}; // initialize foo with 2 elements: 10 and 2

Now the library got a new release and in the new release the author has removed the 2nd constructor that takes a initializer_list (either by purpose or by mistake). I didn't notice the change and my project builds happily as before, only with an unexpected foo being initialized (now it's 10 elements instead of 2).

A different version of this problem is that Foo had only the 1st constructor and you use the universal initialization syntax to init foo, and now the author has decided to add the 2nd constructor and that equally causes foo to be initialized with different elements without being noticed.

Just wanted to know other people's opinion about this. Is it a real problem or am I worrying too much? Is there any solution to prevent this from happening? Thanks.

网友答案:

The real problem is that the API changed.

If the constructor was

Foo(int size, int value);

and you used

Foo foo(10, 2);

and the API would have been changed to

Foo(int value, int size);

you would have the same problem.

分享给朋友:
您可能感兴趣的文章:
随机阅读: