Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c++ - this pointer to base class constructor?

I want to implement a derived class that should also implement an interface, that have a function that the base class can call. The following gives a warning as it is not safe to pass a this pointer to the base class constructor:

struct IInterface
{
    void FuncToCall() = 0;
};

struct Base
{
    Base(IInterface* inter) { m_inter = inter; }

    void SomeFunc() { inter->FuncToCall(); }

    IInterface* m_inter;
};

struct Derived : Base, IInterface
{
    Derived() : Base(this) {}

    FuncToCall() {}
};

What is the best way around this? I need to supply the interface as an argument to the base constructor, as it is not always the dervied class that is the interface; sometimes it may be a totally different class.

I could add a function to the base class, SetInterface(IInterface* inter), but I would like to avoid that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shold not publish this from the constructor, as your object is not yet initialized properly at that point. In this actual situation, though, it seems to be safe, since you are publishing it only to the base class, which only stores it and does not invoke it until some point later, by which time the construction will have been finished.

However, if you want to get rid of the warning, you could use a static factory method:

struct Base
{
public:
    Base() { }

    void setInterface(IInterface* inter) { m_inter = inter; }

    void SomeFunc() { inter->FuncToCall(); }

    IInterface* m_inter;
};

struct Derived : Base, IInterface
{
private:
    Derived() : Base() {}

public:
    static Derived* createInstance() {
        Derived instance = new Derived();
        instance->setInterface(instance);
        return instance;
    }

    FuncToCall() {}
};

Note that the constructor of Derived is private to ensure that instantiation is done only via createInstance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...