test.cpp:10:9: error: cannot jump from switch statement to this case label
case 2:
^
test.cpp:8:17: note: jump bypasses variable initialization
int i=2;
^
1 error generated.
#include<iostream>usingnamespacestd;classA{public:A(){cout<<"normal constructor called in "<<this<<endl;a=10;}A(constA&oth){cout<<"copy constructor called in "<<this<<endl;a=oth.a;}A(A&&oth){cout<<"move constructor called in "<<this<<endl;a=oth.a;}A&operator=(constA&oth){cout<<"operator= called in "<<this<<endl;a=oth.a;return*this;}int&GetA(){returna;}staticAGetInstance(){Atmpa;cout<<"tmpa in GetInstance:"<<&tmpa<<endl;returntmpa;}staticA&&GetMoveInstance(){Atmpa;cout<<"tmpa in GetMoveInstance:"<<&tmpa<<endl;returnstd::move(tmpa);}staticA&GetRefInstance(){cout<<"tmpa in GetRefInstance:"<<&static_a<<endl;returnstatic_a;}private:inta;staticAstatic_a;};AA::static_a;intmain(intargc,char**argv){Aa;cout<<"a's addr:"<<&a<<endl<<endl;Ab=a;cout<<"b's addr:"<<&b<<endl<<endl;A&ra=a;cout<<"ra's addr:"<<&ra<<endl<<endl;Ama=std::move(a);cout<<"ma's addr:"<<&ma<<endl<<endl;Afa=A::GetInstance();cout<<"fa's addr:"<<&fa<<endl<<endl;Afb=A::GetRefInstance();cout<<"fb's addr:"<<&fb<<endl<<endl;A&fra=A::GetRefInstance();cout<<"fra's addr:"<<&fra<<endl<<endl;A&&fma=A::GetMoveInstance();cout<<"fma's addr:"<<&fma<<endl<<endl;return0;}//编译: g++ main.cpp -o main -std=c++11 -fno-elide-constructors //最后的编译选项表示不使用构造函数优化
/**结果
normal constructor called in 0x100f4a100 //这个是static_a的构造函数导致
normal constructor called in 0x7ffeeecb6c98
a's addr:0x7ffeeecb6c98
copy constructor called in 0x7ffeeecb6c90
b's addr:0x7ffeeecb6c90
ra's addr:0x7ffeeecb6c98
move constructor called in 0x7ffeeecb6c80
ma's addr:0x7ffeeecb6c80
normal constructor called in 0x7ffeeecb6bf8
tmpa in GetInstance:0x7ffeeecb6bf8
move constructor called in 0x7ffeeecb6c70
move constructor called in 0x7ffeeecb6c78
fa's addr:0x7ffeeecb6c78
tmpa in GetRefInstance:0x100f4a100
copy constructor called in 0x7ffeeecb6c68
fb's addr:0x7ffeeecb6c68
tmpa in GetRefInstance:0x100f4a100
fra's addr:0x100f4a100
normal constructor called in 0x7ffeeecb6bf8
tmpa in GetMoveInstance:0x7ffeeecb6bf8
fma's addr:0x7ffeeecb6bf8
normal constructor called in 0x7ffee3e1cbe8
tmpa in GetMoveInstance:0x7ffee3e1cbe8
move constructor called in 0x7ffee3e1cc50
fma2's addr:0x7ffee3e1cc50
*/
显然在A a = A::GetInstance()的时候,调用了两次移动构造函数。
在A b = A::GetRefInstance()的情况下仍然会拷贝一次,说明使用非引用得到引用返回值并不能直接饮用(当然改变fb也没办法影响tmpa)。
/**
normal constructor called in 0x7ffee1398c08
tmpa in GetInstance:0x7ffee1398c08
copy constructor called in 0x7ffee1398c70
copy constructor called in 0x7ffee1398c78
fa's addr:0x7ffee1398c78
*/
/**
normal constructor called in 0x7ffeeca22af8
tmpa in GetMoveInstance:0x7ffeeca22af8
deconstructor called in 0x7ffeeca22af8
fma's addr:0x7ffeeca22af8
*/