空inizializer_list上的赋值运算符 [英] assignment operator on empty inizializer_list

查看:91
本文介绍了空inizializer_list上的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能解释一下STL容器如何使用空的初始值设定项列表来处理赋值运算符吗?

can you explain how STL containers handle assignment operator with empty initializer list?

当我要做这样的事情时:

when i'll do something like this:

vector<int> v;
v = { };

被调用的函数为:

vector& operator= (initializer_list<value_type> il);

但是:

vector& operator= (vector&& x);

另一方面,当我要对自己的课堂做类似的事情时:

on the other hand, when i'll do something similar with my own class:

struct A {
    A& operator= (const A&) { return *this; }
    A& operator= (A&&) { return *this; }
    A& operator= (initializer_list<int>) { return *this; }
};

/* ... */

A a;
a = { };

该代码无法在VS2013上编译,并显示:

the code does not compile on VS2013, and says:

error C2593: 'operator =' is ambiguous

如果列表不为空,则工作正常,它仅使用初始化列表调用该函数.该问题仅在列表为空时出现,在vector上它调用右值赋值运算符,在我的类上则给出错误.

if the list is not empty, it works fine, it just calls the function with initializer list. the problem appears only when the list is empty, on vector it calls the rvalue assignment operator, on my class it gives error.

在矢量容器和其他容器中如何处理这种情况?

how this situation is handled in vector and other containers?

推荐答案

这似乎是一个bug叮当声( 实时查看 )和gcc( 观看直播 )接受此程序,然后选择 std :: initializer_list 重载,该重载看起来是正确的,因为这是完全匹配的,对此已进行了介绍在 C ++标准草案部分中示例中的13.3.3.1.5 列表初始化序列段落 2 :

This appears to be a bug clang(see it live) and gcc(see it live) accept this program and choose the std::initializer_list overload which looks correct since that is an exact match, this is covered in the C++ draft standard section section 13.3.3.1.5 List-initialization sequence paragraph 2 from the example:

void f(std::initializer_list<int>);
f( {1,2,3} ); // OK: f(initializer_list<int>) identity conversion
f( {’a’,’b’} ); // OK: f(initializer_list<int>) integral promotion
f( {1.0} ); // error: narrowing

我们进行了身份转换,这是完全匹配.

对于参考超载,我们转到段落 5 ,其中说(强调我的前进):

For the reference overloads we go to paragraph 5 it says (emphasis mine going forward):

否则,如果参数是引用,请参见13.3.3.1.4. [注意:本节中的规则将适用于初始化供参考的基础临时文件. —尾注]

表示已创建临时文件,然后我们可以将规则应用于生成的临时文件.这将是用户定义的转换,比完全匹配更糟糕.

indicates that temporary is created an then we can apply the rules to resulting temporary. This will be a User-defined conversion which is worse than an exact match.

所以这应该不是模棱两可的.

So this should not be ambiguous.

更新

好像有两个与此相关的活动错误:

Looks like there are two active bugs related to this:

  • Compiler confused about whether to use a initializer_list assignment operator
  • VC++ 12 RC fails to choose between initializer_list enabled assignment operator and canonical one for std::pair list elements

这篇关于空inizializer_list上的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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