简体   繁体   中英

Why int& a=10; is valid in ancient C++ compilers?

I was just wondering why ancient compilers like Turbo c++ 3.0(Blue screen IDE) & Borland Turbo C++ 4.5 etc doesn't report any error in following program.

#include <iostream.h>
int main()
{
  int& a=10;
  cout<<a;
  return 0;
}

The above program won't be accepted by modern C++ compilers, But why then ancient compilers allows this? They simply shows single warning in above program.

It used to be valid C++ to bind a reference to a temporary, so you could pass eg double to a function expecting int& , as explained in The Design & Evolution of C++ §3.7:

I made one serious mistake, though, by allowing a non- const reference to be initialized by a non-lvalue. [...]
The reason to allow references to be initialized by non-lvalues was to allow the distinction between call-by-value and call-by-reference to be a detail specified by the called function and of no interest to the caller. For const references, this is possible, for non- const references it is not. For Release 2.0 the definition of C++ was changed to reflect this.

In C++ 2.0 (and in ISO C++) temporaries can only be bound to const references.

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