c++临时对象初始化指针和引用

出现这种疑问时,可以尝试换个编译器……比如 g++main.cpp:5:11: error: \u0026#39;::main\u0026#39; must return \u0026#39;int\u0026#39; void main() ^main.cpp: In function \u0026#39;int main()\u0026#39;:main.cpp:7:23: error: invalid initialization of non-const reference of type \u0026#39;base\u0026amp;\u0026#39; from an rvalue of type \u0026#39;base\u0026#39; base\u0026amp; ref3 = base(); ^main.cpp:8:22: error: taking address of temporary base* p1 = \u0026amp;base(); ^比如 clang++main.cpp:5:1: error: \u0026#39;main\u0026#39; must return \u0026#39;int\u0026#39;void main()^~~~intmain.cpp:7:11: error: non-const lvalue reference to type \u0026#39;base\u0026#39; cannot bind to a temporary of type \u0026#39;base\u0026#39; base\u0026amp; ref3 = base(); ^ ~~~~~~main.cpp:8:16: error: taking the address of a temporary object of type \u0026#39;base\u0026#39; base* p1 = \u0026amp;base(); ^~~~~~~3 errors generated.
■网友
我猜VS2013可能开了C++11,直接撸了move?
■网友
这充分证明了C++代码和VC++代码是不同的。。换个正常的编译器。
■网友
1.因为你开启了VS2013的非标准扩展.你把警告等级W4开了就知道了.这是微软搞得2.一样是非标准扩展nonstandard extension used : class rvalue used as lvalue
■网友
gcc version 4.7.1首先,base()是产生的确实是一个临时对象(temporary)c++临时对象初始化指针和引用
【c++临时对象初始化指针和引用】
1. 对于base\u0026amp; ref3 = base();编译器报错:error: invalid initialization of non-const reference of type \u0026#39;base\u0026amp;\u0026#39; from an rvalue of type \u0026#39;base\u0026#39;|也就是对于临时变量的引用只能是const reference改为const base\u0026amp; ref3 = base();后此行代码编译通过。对了,C++11标准中引入了右值引用,临时变量属于右值,所以也可以写成:base\u0026amp;\u0026amp; ref3 = base();2. 对于base* p1 = \u0026amp;base();编译器报错:error: taking address of temporary |即标准C++禁止对临时变量取地址操作。将此行注释掉,编译通过。@Sunchy321 引用楼上的一句话,这充分证明了C++代码和VC++代码是不同的。


    推荐阅读