简体   繁体   中英

Use cases for two-phase initialization

I've seen a lot of two-phase initialization used. The justification is to call virtual functions from the secondary constructor. However, I've never, ever, seen any use case in which this was necessary. Are there any?

在不支持异常的平台上,或者由于异常处理导致的代码大小增加是不可接受的,两阶段初始化允许您在辅助构造函数中放置可能失败的活动。

No, it's never unavoidable.

In the worst case, this simply calls for a builder function (which may be selected by runtime mechanisms) returning an optional wrapper around the object.

In C++11, with movable types, there is not even a need for dynamic allocation, simply returning a boost::optional<T> is enough.

Of course, it does change from calling a constructor directly to calling a builder function/factory. But I prefer the additional burden to a two-phase initialization any day. Because I don't get no partial object that way!

One way in which I've seen virtual functions called from a constructor in other languages, which cannot be done in a C++ constructor, is:

class AController
{
};

class A
{
private:
    // This is only a raw pointer that never gets freed for simplicity
    // The real code does ensure it gets freed when appropriate
    AController *controller;
protected:
    virtual AController *CreateController()
    {
        return new AController();
    }
public:
    A()
    {
        controller = CreateController();
    }
};

class BController : public AController
{
};

class B : public A
{
protected:
    virtual AController *CreateController()
    {
        return new BController();
    }
};

A is a complex object, with several Controller -like subobjects (I've only included one), each of which can be derived from (if appropriate) independently. In C++, the CreateController -like functions must be called after the constructors have finished, or no BController -like objects will ever be created.

It's possible to avoid requiring explicitly calling Initialize() methods, but Initialize() methods (called from a helper function that also performs the new A() ) are one of the simpler ways to go.

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