简体   繁体   中英

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?

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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM