在MSVC中引用一个临时文件 [英] Reference a temporary in 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() );
}
这仅适用于使用构造函数临时创建的对象。
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..
推荐答案
它可以编译,但不能与其他右值一起使用,例如(myClass()+ myClass())。因为MSVC具有一个非标准的扩展名,该扩展名允许将非const引用绑定到临时对象。
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中引用一个临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!