简体   繁体   中英

placement new for member variable

I have a class that has a member variable for GUI. I have to supply the text, font and size at construction. Unfortunately the constructor of the owning class does not get this data supplied but has to get it from factories (especially the font).

class Element {
public:
    Element();
    /* other stuff */

private:
    UIElement uie;
};

Element::Element() /* cannot construct the object here */ {
    /* ... some aquiring ... */
    new (&uie) UIElement(/* now I have the required data */);
}

Is this a valid implementation? Can I simply place the object into the space that is already allocated by the construction of the Element class?

You comment in the code /* cannot construct the object here */ , but the fact is that the member is constructed before the compound statement is entered.

Is this a valid implementation? Can I simply place the object into the space that is already allocated by the construction of the Element class?

No. The default constructed member would have to be destroyed first, before you can use placement new - unless the member is trivially destructible.

This is quite pointless however. Whatever you can do within the compound statement, you probably can do within the initialization list as well. If one expression is not enough, then you can simply write a separate function, and call that.

UIElement init_uie(); // could be a member if needed
Element::Element() : uie(init_uie()) {

One option is to factor out the initialization code like this:

Element::Element() : uie(get_uie()) {}

UIElement get_uie(){
    /* ... some aquiring ... */
    return UIElement(/* now I have the required data */);
}

You can also do it inline without the extra function like this, but arguably it is difficult to read:

Element::Element() : uie(
    []{
        /* ... some aquiring ... */
        return UIElement(/* now I have the required data */);
    }()
){}

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