在 msvc 中引用临时文件

2021-12-22 00:00:00 visual-c++ c++

为什么这会在 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]

相关文章