Following wrong code compiles and executes properly with 'g++ -Wall -O2', but
compiles and terminates with std::bad_alloc() 'g++ -Wall'. In both cases
expected behaviour would have been an error from compiler stating that it is
not possible to initialize a const long & with a const double &. gcc errors out
as expected with non const references.
$>cat reference_test.cc
#include <valarray>
#include <iostream>
using namespace std;

template<class Value>
class T
{
  const long &dim;
public:
  T(const double &_dim) : dim(_dim)
  {
    cout << dim << endl;
  }
  Value newValue()
  {
    cout << dim << endl;
    return Value(dim);
  }
};

int main(int argc, char *argv[])
{
  long dim = 10;
  cout << dim << endl;
  T< valarray<double> > factory(dim);
  valarray<double> tmp = factory.newValue();
}

$>g++-4.3.4 -Wall reference_test.cc
$>./a.out
10
10
46934497319904
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted
$>g++-4.3.4 -Wall -O2 reference_test.cc
$>./a.out
10
10
10

$>g++-4.3.4 -v
Using built-in specs.
Target: x86_64-unknown-linux-gnu
Configured with: ../gcc-4.3.4/configure --enable-__cxa_atexit
--disable-multilib --enable-languages=c++ --prefix=/iuehome/schnass/gcc-4.3.4
Thread model: posix
gcc version 4.3.4 (GCC)


-- 
           Summary: Initialization of reference with temporary
           Product: gcc
           Version: 4.3.4
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: devh at stuffit dot at
 GCC build triplet: x86_64-unknown-linux-gnu
  GCC host triplet: x86_64-unknown-linux-gnu
GCC target triplet: x86_64-unknown-linux-gnu


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=40970

Reply via email to