Virtual inheritance doesn't break static composition?

前端 未结 3 1854
执笔经年
执笔经年 2020-12-15 13:53

I was working the last 5 years with the assumption that virtual inheritance breaks static composition.

But now I discovered, that static composition is still maintai

3条回答
  •  眼角桃花
    2020-12-15 14:42

    Maybe I'm dumb, but I don't understand what you mean by "static composition." You say pimpl breaks it, so let's start with that and take polymorphism and virtual inheritance out of it.

    Suppose you have this code:

    #include 
    using namespace std;
    
    class Implementation
    {
    public:
        bool do_foo() { return true; }
    };
    
    class Implementation2
    {
    public:
        bool do_foo() { return false; }
    private:
        char buffer_[1024];
    };
    
    class Interface
    {
    public:
        Interface(void* impl) : impl_(impl) {};
        bool foo() { return reinterpret_cast(impl_)->do_foo(); }
        void change_impl(void* new_impl) { impl_ = new_impl; }
    
    private:
        void* impl_;
    };
    
    int main()
    {
        Implementation impl1;
        Implementation2 impl2;
    
        Interface ifc(&impl1);
        cout << "sizeof(ifc+impl1) =  " << sizeof(ifc) << "\n";
    
        Interface ifc2(&impl2);
        cout << "sizeof(ifc2+impl2) =  " << sizeof(ifc2) << "\n";
    
        ifc.change_impl(&impl2);
        cout << "sizeof(ifc+impl2) =  " << sizeof(ifc) << "\n";
    
        cout << "sizeof(impl) = " << sizeof(impl1) << "\n";
        cout << "sizeof(impl2) = " << sizeof(impl2) << "\n";
    
    }
    

    When you say "breaks static composition" do you mean the sizeof things change as you change out the pimpl in the interface?

提交回复
热议问题