0

So I have a storage class that has a ton of basic functionality that is really useful as is. It has move constructors to allow return by value.

class A
{
public:
    virtual ~A(){}
    A(const A& a);
    A(A&& a);
    A& operator=(const A& rhs);
    A& operator=(A&& rhs);
    int foo();//example member function
    //example function returning by value, elision and RHR make it efficient
    static A Foo();
};

This is great because it allows who own A to be very well defined. If I start needed to have inherited classes that extend A, AND the return statement of a call function to have polymorphism, is the only "correct" way to use smart pointers? AKA

class B_interface : public A
{
public:
    virtual ~B_interface(){}
    virtual void FooBar() = 0;
};

class B : public B_interface
{
public:
    virtual ~B(){}
    B(const B& a);
    B(B&& a);
    B& operator=(const B& rhs);
    B& operator=(B&& rhs);
    virtual void FooBar() override;
    static shared_ptr<B> idontlikeit();
}

I thought of a (probably bad) way to get around it: if, instead of inheritance, use composition: the class contains something akin to a impl ptr:

class B_interface
{
public:
    virtual void FooBar() = 0;
};


class B : public A
{
    shared_ptr<B_interface> impl_;//could use 
public:
    B(const A& a,shared_ptr<B_interface> interface)//or some smarter way to pass this in
    : A(a)//call a's copy constructor
    {
       impl_.reset(interface);
    }//this constructor thinks

    void FooBar() { impl_->FooBar();}
    virtual ~B(){}
    B(const B& a);
    B(B&& a);
    B& operator=(const B& rhs);
    B& operator=(B&& rhs);
    static B ilikeitbetter();
}

So I like using the class better with that one, but making the class kinda stinks with that one...also, the B_interface might not make much sense outside B...Do you guys have any alternatives?

4

1 回答 1

1

是的,运行时多态性需要动态分配和指针。派生类可以(并且通常是)与基类不同的大小,因此期望值语义的代码将不知道为值类型保留多大的块。

在这种特定情况下,unique_ptr<Interface>如果您不希望调用者需要共享语义,请考虑返回 a。这样你就不会强迫调用者在不需要时进行引用计数。(调用者总是可以将所有权从 转移unique_ptr到 ashared_ptr如果他们想要共享语义)

于 2013-07-02T17:10:04.027 回答