我是C编程的初学者,但我想知道typedef在定义结构时使用与使用结构之间有什么区别typedef.在我看来,实际上没有区别,他们实现了同样的目标.
struct myStruct{
int one;
int two;
};
Run Code Online (Sandbox Code Playgroud)
与
typedef struct{
int one;
int two;
}myStruct;
Run Code Online (Sandbox Code Playgroud) §3.10第9节说"非类别rvalues总是有cv不合格类型".这让我很奇怪......
int foo()
{
return 5;
}
const int bar()
{
return 5;
}
void pass_int(int&& i)
{
std::cout << "rvalue\n";
}
void pass_int(const int&& i)
{
std::cout << "const rvalue\n";
}
int main()
{
pass_int(foo()); // prints "rvalue"
pass_int(bar()); // prints "const rvalue"
}
Run Code Online (Sandbox Code Playgroud)
根据标准,对于非类型类型没有const rvalue,但bar()更喜欢绑定const int&&.这是编译器错误吗?
编辑:显然,this也是一个const rvalue :)
编辑:这个问题似乎在g ++ 4.5.0中得到修复,现在两行打印"rvalue".
让我们采取两个结构/类
struct C1{
C1(){};
C1(C1&){std::cout<<"copy"<<std::endl;}
C1(C1&&){std::cout<<"move"<<std::endl;}};
struct C2{
C1 c;
C2(){};
C1 get1(){return c;}
C1 get2(){return std::move(c);}};
Run Code Online (Sandbox Code Playgroud)
然后
C1 a1=C2().c;
C1 a2=C2().get1();
C1 a3=C2().get2();
Run Code Online (Sandbox Code Playgroud)
输出是
move
copy
move
Run Code Online (Sandbox Code Playgroud)
我们知道rvalues的成员本身就是rvalues.这就是为什么使用a1,调用移动构造函数.为什么,在a2的情况下调用复制构造函数.我们从函数返回一个rvalue.
换句话说,std :: move强制转换为右值.但是,作为一个rvalue的成员,c,已经是一个rvalue.为什么a2和a3的行为之间存在差异?