简体   繁体   中英

Object creation in constructor

I somehow read that it is bad style to do object-creation in a constructor ... however, I forgot why it was considered to be bad style (especially when using dependency injection).

Here an example of object-creation in the constructor as pseudo-code:

Myclass
{
    Myclass(MyMemberFactory& fac)
    {
        for(Some criteria)
            push_back(fac.createMyMemberType());
    }

    vector<MyMemberType*> getMyMember();
    {
        return myMember_;
    }
    ...

private:
    vector<MyMemberType*> myMember_;
}

So you can use unit-testing without problems, because you can mock-away the MyMemberFactory. If I would move the for-loop in an seperated initialize-method, it would be necesarry to check for double-initialisation, and all getters would need first to ckeck, if initialisation already was done. Here the code, by using a seperate initialisation:

Myclass
{
    Myclass() : isInitialized_(false)
    {

    }

    void initialize(MyMemberFactory& fac);
    {
        if(isInitialized_)
            throw "Error: Double-Init is not permitted.";

        for(Some criteria)
            push_back(fac.createMyMemberType());

        isInitialized_ =true;
    }

    vector<MyMemberType*> getMyMember();
    {
        if(isInitialized_)
            throw "Initialize first!";

        return myMember_;
    }
    ...

private:
    vector<MyMemberType*> myMember_;
    bool isInitialized_;
}

So do know any reason, why I should use the second approach over the first approach? Or maybe I just had something wrong in mind, and the first approach is perfectly ok?

如果构造函数引发异常,则不会调用析构函数,因此您将丢失所有手动分配的内存。

The first approach is actually fine. It's not that object creation in a constructor is problematic, it's that doing so with a constructor is problematic. So

Myclass()
{
    MyMemberFactory fac;
    for(Some criteria)
        push_back(fac.createMyMemberType());
}

Would be problematic since clients can no longer use a different factory (for testing, for instance).

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