vendredi 24 février 2017

Is it defined behavior to use placement new to change type of variable that is held by reference_wrapper?

I was messing with placement new, and made this code:

#include <iostream>
#include <functional>
#include <new>

int main()
{
    char memory[sizeof(int)]; //memory to hold type
    auto ref = std::ref(*new (memory) int{5}); //allocating int in memory, and make a reference to it
    std::cout << ref << std::endl;
    new (memory) unsigned{6}; //"overwrite"
    std::cout << ref << std::endl;
}

The output is 5 then 6, but is it well defined? If so, would it be okay if I used float as second type instead?

Aucun commentaire:

Enregistrer un commentaire