2

what will happen to the reference to an object after destruction and creation in-place of that object? Will it be still valid or it is undefined behavior? Here is an example:

#include <iostream>

class A
{
    int var;

public:
    A(int var) : var(var) {}

    void foo()
    {
        std::cout << var;
    }
};

A obj(5);

void main()
{
    A& ref = obj;
    obj.~A();
    new (&obj) A(6);
    
    ref.foo();  // is this valid?
}
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
legier
  • 129
  • 1
  • 9
  • 6
    Specified in https://timsong-cpp.github.io/cppwp/n4861/basic.life#8, and it is likely that similar questions have been asked before. – Language Lawyer Mar 25 '21 at 08:07
  • 2
    Colour me surprised. That's the sort of thing I'd expect to "work", but be technically illegal. Nice to see the Standard canonizes it with a relatively short list of caveats. – user4581301 Mar 25 '21 at 08:14

0 Answers0