适用于会员变量的新位置



我有一个具有GUI成员变量的类。我必须在施工时提供文本,字体和尺寸。不幸的是,拥有类的构造函数没有提供此数据,而是必须从工厂(尤其是字体(获取数据。

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 */);
}

这是有效的实现吗?我可以简单地将对象放入已通过Element类构建已经分配的空间?

您在代码/* cannot construct the object here */中发表评论,但事实是在输入复合语句之前构建了成员

这是有效的实现吗?我可以简单地将对象放入已经通过元素类构建已经分配的空间吗?

否。默认的构造成员必须首先被销毁,然后您才能使用新的位置 - 除非成员可以在易于破坏。

这是毫无意义的。无论您在复合语句中可以做什么,您也可以在初始化列表中执行。如果一个表达式还不够,那么您可以简单地编写一个单独的函数,然后调用。

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

一个选项是将这样的初始化代码计算出来:

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

您也可以在没有这样的额外功能的情况下内联行动,但是可以说很难阅读:

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

最新更新