return 类型的列表初始化是什么?
what is the return type of list initialisation?
有没有人想解释一下为什么案例 1 和案例 2 对于此代码段有不同的输出。
struct A {
A() { cout << "A()" << endl; }
A(int i) { cout << "A(int)" << endl; }
A(const A&) { cout << "A(const A&)" << endl; }
A(A&&) noexcept { cout << "A(A&&)" << endl; }
A& operator=(const A&) { cout << "operator=(const A&)" << endl; return *this; }
A& operator=(A&&) noexcept { cout << "operator=(A&&)" << endl; return *this; }
friend bool operator< (const A&, const A&) { return true; }
};
int main() {
std::set<A> aSet;
aSet.insert(1); // case 1
//aSet.insert({1}); // case 2
return 0;
}
对于情况 1,输出为:
A(int)
A(A&&)
案例 2 是:
A(int)
A(const A&)
编译器版本为:
g++ --version
g++-7 (SUSE Linux) 7.2.1 20170901 [gcc-7-branch revision 251580]
Copyright (C) 2017 Free Software Foundation, Inc.
std::set::insert
的相关重载是:
std::pair<iterator,bool> insert( value_type const& value ); // #1
std::pair<iterator,bool> insert( value_type&& value ); // #2
void insert( std::initializer_list<value_type> ilist ); // #6
当您调用 aSet.insert(1);
时调用 #2 优先于 #1 - 这将通过 A(int )
创建一个新的 A
然后将其移动到集合中。因此,A(A&& )
.
但是,当您调用 aSet.insert({1})
时,选择的重载是 #6。每当您使用列表初始化时,std::initializer_list
候选者是 强烈首选 (基本上,我们首先 只 考虑这些候选者和然后,只有当我们找不到一个时,我们才会考虑其余的重做重载决议)。由于 std::initializer_list
由 const
array 支持,一旦我们通过 A(int )
创建了 A
,我们 必须 复制它 - 我们不能移动它。因此 A(A const& )
.
有没有人想解释一下为什么案例 1 和案例 2 对于此代码段有不同的输出。
struct A {
A() { cout << "A()" << endl; }
A(int i) { cout << "A(int)" << endl; }
A(const A&) { cout << "A(const A&)" << endl; }
A(A&&) noexcept { cout << "A(A&&)" << endl; }
A& operator=(const A&) { cout << "operator=(const A&)" << endl; return *this; }
A& operator=(A&&) noexcept { cout << "operator=(A&&)" << endl; return *this; }
friend bool operator< (const A&, const A&) { return true; }
};
int main() {
std::set<A> aSet;
aSet.insert(1); // case 1
//aSet.insert({1}); // case 2
return 0;
}
对于情况 1,输出为:
A(int)
A(A&&)
案例 2 是:
A(int)
A(const A&)
编译器版本为:
g++ --version g++-7 (SUSE Linux) 7.2.1 20170901 [gcc-7-branch revision 251580] Copyright (C) 2017 Free Software Foundation, Inc.
std::set::insert
的相关重载是:
std::pair<iterator,bool> insert( value_type const& value ); // #1
std::pair<iterator,bool> insert( value_type&& value ); // #2
void insert( std::initializer_list<value_type> ilist ); // #6
当您调用 aSet.insert(1);
时调用 #2 优先于 #1 - 这将通过 A(int )
创建一个新的 A
然后将其移动到集合中。因此,A(A&& )
.
但是,当您调用 aSet.insert({1})
时,选择的重载是 #6。每当您使用列表初始化时,std::initializer_list
候选者是 强烈首选 (基本上,我们首先 只 考虑这些候选者和然后,只有当我们找不到一个时,我们才会考虑其余的重做重载决议)。由于 std::initializer_list
由 const
array 支持,一旦我们通过 A(int )
创建了 A
,我们 必须 复制它 - 我们不能移动它。因此 A(A const& )
.