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++临时对象初始化指针和引用】
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++代码是不同的。
推荐阅读
- 出入口■注意了!南京地铁两个出入口将临时封闭
- 非计算机专业想要利用课余时间深入自学C++,想要找到比较体面的工作大概需要啥水平
- Java工程师和C++工程师在工作上有啥区别哪个更适合自身发展
- |高架施工 这些上匝道将临时管制
- 结婚对象的抉择
- 咨读君|交警提醒:即日起,这些汽车禁止上路,已经成为严查对象
- |受吉兴西路道路施工影响 扬州这条公交线路走向临时调整
- C、C++、java等编程语言都有哪些坑
- 网传襄阳一批发市场着火,实为一临时仓库!
- c++写http服务器不用cgi和apache该用啥
