Reference a temporary in msvc

前端 未结 2 600
耶瑟儿~
耶瑟儿~ 2020-12-04 04:07

Why does this compile on MS Visual C++?

struct myClass{};

void func(myClass& arg){}

void main() {
   func( myClass() );  // works even though func only         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 04:37

    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 produces:

    error: taking the address of a temporary object of type 'Foo' [-Waddress-of-temporary]

    while GCC 4.7.3 produces

    error: taking address of temporary [-fpermissive]

提交回复
热议问题