c++11和c++14新特性中auto、智能指针、移动语义、lambda表达式、并发等等相关内容
item7 创建对象时区分()和{}
- 大括号语境最为广泛,阻止隐士窄化型别转换,对most vexing parse免疫
double x, y, z;
int sum1{x + y + z};
int sum2(x + y + z);
int sum3 = x + y + z;
Widget w();
Widget w2{};
- 在函数重载期间,只要有可能,大括号初始化物会与initialize_list型别的形参相匹配,即使有更匹配的形参列
#include <iostream>
using namespace std;
class Widget{
private:
double i_;
public:
double GetVal(){
return i_;
}
Widget(){
cout<<"default ctor"<<endl;
}
Widget(double i):i_(i){
cout<<"param ctor"<<endl;
}
Widget(const Widget &rhs){
cout<<"copy ctor"<<endl;
i_ = rhs.i_;
}
Widget& operator=(const Widget &rhs){
cout<<"copy assignment"<<endl;
i_ = rhs.i_;
return *this;
}
Widget (std::initializer_list<long double> arg){
std::cout << "initializer call" << std::endl;
}
operator double(){
cout<< "double call" <<endl;
return i_;
}
};
int main(int argc, char const *argv[])
{
Widget w1 {};
return 0;
}
- 使用大括号还是小括号效果不一样的例子是:使用两个参数来创建std::vector对象
vector<int> v1(10, 20);
vector<int> v2{10, 20};
|