Placing a new one for a member variable

I have a class that has a member variable for the GUI. I have to provide text, font and size when building. Unfortunately, the constructor of the owner class does not receive this data, but must 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 version? Can I just put the object in the space that is already allocated by the class construct Element

?

+3


source to share


2 answers


You will comment out the code /* cannot construct the object here */

, but the fact is that the element is created before the compound statement is entered.

Is this a valid version? Can I just put the object in the space that is already allocated by the construct of the Element class?

Not. The default created element must be destroyed first before you can use the new placement - unless the element is trivially destructible.



It's completely pointless. Whatever you do in a compound statement, you can probably do in an initialization list as well. If one expression isn't enough, you can just write a separate function and call that.

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

      

+2


source


One option is to reverse 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 additional function like this, but it might be hard to read:

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

      

+1


source







All Articles