1.深入理解 explicit
https://blog.csdn.net/fengbingchun/article/details/51168728
C++中的关键字explicit主要是用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换。类构造函数默认情况下声明为隐式的即implicit。
隐式转换即是可以由单个实参来调用的构造函数定义了一个从形参类型到该类类型的隐式转换。编译器在试图编译某一条语句时,如果某一函数的参数类型不匹配,编译器就会尝试进行隐式转换,如果隐式转换后能正确编译,编译器就会继续执行编译过程,否则报错。
个人意见 注重各种赋值过程的类型隐士转换
class String{
public:
explicit String(int n) {};
String(const char *p) {};
};
static void test1()
{
//String s1 = 'a'; // 错误:不能做隐式char->String转换
String s2(10); // 可以:调用explicit String(int n);
String s3 = String(10); // 可以:调用explicit String(int n);再调用默认的复制构造函数
String s4 = "Brian"; // 可以:隐式转换调用String(const char *p);再调用默认的复制构造函数
String s5("Fawlty"); // 可以:正常调用String(const char *p);
}
static void f(String)
{
}
static String g()
{
//f(10); // 错误:不能做隐式int->String转换
f("Arthur"); // 可以:隐式转换,等价于f(String("Arthur"));
//return 10; // 同上
}
void test_explicit()
{
test1();
g();
}
2.for each 语法
for each ( declare : coll) {
statement
}
etc:
for each ( auto & element : vector<type>) {
statement
}
//if no &,there will be a local copy,that couldn't change the source data.yet the source data is protected.
//the best:
for each ( const auto & element : vector<type>) {
statement
}
//the advantage of this mean couldn't change the source data and don't call constructor and destructor .
3. Move semantic (move语义)&Rvalue Reference (右值引用)
避免非必要拷贝和临时对象。
this feature is complex.
当某个变量最后一次使用场景,应该尽量std::move,即直接使用他本身。if no move ,call copy constructor.
self move函数注意事项,此处不细说了。
举个栗子:把局部数据按右值返回出去,是错误的,因为局部变量会被释放掉,在去引用发生错误。那么move一下,就ok了。
int && fun()
{
int a{ 111 };
cout << a << endl;
return std::move(a);
}
int reta = fun();
cout <<"reta" <<reta << endl;
今天就到这儿了,a bit tired.