Search code examples
c++new-operatorassignment-operatorcopy-assignment

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?


Solution

  • You should not do this, though it will technically work in this case.

    By circumventing the copy assignment you are not giving the object a chance to perform any required cleanup on the old data (e.g. freeing memory resources). In this example, you are calling the new placement operator before the lifetime of a ends.

    The following will work as it does not violate a's lifetime:

    a.~A(); // manually destruct a, end it's lifetime
    new(&a) A(69); // construct a new instance and start a new lifetime