placement new to circumvent assignment constructor

Is it a viable solution to use placement new to circumvent copy assignment?

I have a member object that contains const members.
The object itself is meant to be created at runtime, but it’s members are meant to be const.

I was wondering whether I could use placement new to circumvent the copy assignment at runtime?

#include <new>
#include <iostream>
struct A {
    const int a;
    A() : a(0) {};
    A(int a) : a(a){}
};

struct B {
    A a;
    void createA() {
        new(&a) A(69);
    }

    void useA() {
        std::cout << a.a << std::endl;
    }

};

int main(void) {

    B b;
    b.createA();
    b.useA();
    return 0;
}

It compiles and runs but does it invoke UB?

Source: Windows Questions C++

LEAVE A COMMENT