mardi 3 novembre 2015

Is it legal to change what a reference is bound to by using placement new operator? [duplicate]

This question already has an answer here:

This is an offshoot of Using placement new to update a reference member?.

It seems that I am able to change what a reference is bound to by using a placement new operator:

#include <iostream>

struct Foo
{
   Foo(int& v) : v_(v)
   {
      std::cout << v_ << std::endl;
   }

   int& v_;
};

int main()
{
   int a = 10;
   int b = 20;

   Foo f(a);
   std::cout << "f.v_: " << f.v_ << std::endl;
   new (&f)Foo(b);
   std::cout << "f.v_: " << f.v_ << std::endl;
   b = 30;
   std::cout << "f.v_: " << f.v_ << std::endl;
}

Output with g++ 4.9.3 in cygwin64:

10
f.v_: 10
20
f.v_: 20
f.v_: 30

It's clear that f.v_ was bound to a before the call to the placement new operator but is bound to b after the call. Is this legal?

EDIT

This answer by T.C. answers this question too.

Aucun commentaire:

Enregistrer un commentaire