简体   繁体   中英

Does C++11 permit taking a reference to an anonymous temporary

I have a function void foo(const std::string& s) which I'd like to call using foo(s.substr(pos)) .

In MSVC (implementing C++98), this compiled fine, but an old compiler for posix would error with "cannot take a reference of an anonymous temporary". That makes me think that taking a reference to an anonymous temporary is not permitted in standard C++98.

But, is it permitted in C++11?

C++98 as well as C++11 accept a temporary when binding a const reference as a parameter. The following works:

void foo( const std::string& s );

foo( s.substr( pos ) ); // OK

If you want to take a non-const reference, the standard/compiler sees this as a hint that you need the modified result, which is impossible to access as it is a temporary. Hence the following does not work:

void foo( std::string& s );

foo( s.substr( pos ) ); // not OK

Note that with C++11, you can overload foo to detect rvalues, which temporaries are. (There are others):

void foo( std::string& s ); // 1
void foo( std::string&& s ); // 2

foo( s.substr( pos ) ); // calls 2

Does C++11 permit taking a reference to an anonymous temporary?

Yes, absolutely . So does C++03. With conditions...

In MSVC (implementing C++98), this compiled fine, but an old compiler for posix would error with "cannot take a reference of an anonymous temporary". That makes me think that taking a reference to an anonymous temporary is not permitted in standard C++98.

I think you're remembering something slightly different. Firstly, all temporaries are "anonymous", and they can all be bound to a reference-to- const (the binding extends the lifetime of the temporary, though in the following example even that is not necessary):

int foo(const T&);
int x = foo(T());

This was always the case in standard C++ and before. If your old POSIX compiler did not accept it then it was horribly broken; however, I believe you're instead thinking of the following case:

int foo(T&);  // no `const`
int x = foo(T());

This is not legal, but Visual Studio ( only ) accepts it as a misguided non-standard exception, because Microsoft.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM