Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c++ - Reference a temporary in msvc

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&!!)

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...