C ++ 11通用初始化导致意外的初始化? [英] C++11 universal initialization cause unexpected initialization?

查看:171
本文介绍了C ++ 11通用初始化导致意外的初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,新的通用初始化语法也可以用于调用普通构造函数(不使用initializer_list参数)。虽然看起来不错,我认为这可能会导致现实世界使用中的问题。



因此,假设在我的项目中,我使用了一个库, :

  class Foo 
{
public:
Foo(int size,int value) ; // create'size'number of elements
Foo(initializer_list< int> list); //在'list'中创建元素
}

这样:

  Foo foo {10,2}; //用2个元素初始化foo:10和2 

现在库获得了一个新版本,新版本的作者已经删除了第二个构造函数需要一个initializer_list(目的或错误)。我没有注意到这个变化,我的项目像以前一样快乐,只有一个意外的foo被初始化(现在是10个元素,而不是2)。



这个问题是Foo只有第一个构造函数,并且使用通用初始化语法来初始化foo,现在作者决定添加第二个构造函数,同样导致foo用不同的元素初始化,而不被注意。 p>

只是想知道其他人对此的意见。这是一个真正的问题还是我担心太多?有没有任何解决方案来防止这种情况发生?谢谢。

解决方案

真正的问题是API改变了。



构造函数是

  Foo(int size,int value); 

您使用

  Foo foo(10,2); 

,API将更改为

  Foo(int value,int size); 

你会有同样的问题。


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.

这篇关于C ++ 11通用初始化导致意外的初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆