Reference a temporary in msvc(在 msvc 中引用临时文件)
问题描述
为什么这会在 MS Visual C++ 上编译?
Why does this compile on MS Visual C++?
struct myClass{};
void func(myClass& arg){}
void main() {
func( myClass() ); // works even though func only takes myClass&
} // (not const myClass&!!)
这是否也适用于其他编译器,或者是特定于 MSVC 的(甚至是编译器错误?).我什至可以像这样获得这个右值的引用:
Does this work on other compilers as well or is this MSVC specific (or even a compiler bug?). I can even get the reference on this rvalue like this:
void func(myClass* arg){}
int main() {
func( &myClass() );
}
这仅适用于使用构造函数临时创建的对象.这不适用于任何其他右值,例如 (myClass() + myClass()) ..
This works ONLY on Objects that are temporarily created with a constructor. This wouldn't work with any other rvalue like (myClass() + myClass()) for example..
推荐答案
它可以编译是因为 MSVC 有一个非标准兼容的扩展",允许将非常量引用绑定到临时文件.
It compiles because MSVC has a non-standard compliant "extension" that allows binding non-const references to temporaries.
第一个示例不应在符合标准的编译器上编译.
The first example should not compile on a standards compliant compiler.
在第二个示例中,您将使用临时地址来设置指针的值.这也应该导致错误.
In the second example, you are taking the address of a temporary to set the value of a pointer. This should also result in an error.
Clang 3.2 产生:
Clang 3.2 produces:
错误:获取类型为 'Foo' [-Waddress-of-temporary] 的临时对象的地址
error: taking the address of a temporary object of type 'Foo' [-Waddress-of-temporary]
而 GCC 4.7.3 产生
while GCC 4.7.3 produces
错误:取临时地址[-fpermissive]
error: taking address of temporary [-fpermissive]
这篇关于在 msvc 中引用临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 msvc 中引用临时文件


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01