2013-07-02 2 views
0

그래서 정말 유용한 기본 기능을 가진 저장소 클래스가 있습니다. 가치에 의한 반환을 허용하는 이동 생성자가 있습니다.가치와 다형성으로 돌아 가기

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(); 
}; 

이것은 누가 A를 매우 잘 정의 할 수 있기 때문에 좋습니다. 필자가 A를 확장 한 상속 된 클래스를 갖기 시작하고 호출 함수의 return 문이 다형성을 가지기 시작하면 스마트 포인터를 사용하는 유일한 "올바른"방법입니까? 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(); 
} 

나는 그것을 해결하기 위해 (아마도 나쁜) 방법을 생각 : 대신 상속의 사용 조성물 경우 : 클래스가 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(); 
} 

을 그래서 클래스를 클래스와 함께 사용하는 것이 좋지만 클래스를 좀 더 악취로 만드는 것은 ... B_interface는 B 외부에서별로 의미가 없을 수도 있습니다 ... 다른 대안이 있습니까?

답변

1

예, 런타임 다형성에는 동적 할당 및 포인터가 필요합니다. 파생 클래스는 기본 클래스와 다른 크기 일 수 있으며 일반적으로 코드 의미 값 개념은 값 유형에 대해 예약 할 블록의 크기를 알 수 없습니다.

이 특정 경우에는 호출자가 공유 의미를 필요로하지 않을 경우 unique_ptr<Interface>을 반환하는 것이 좋습니다. 그렇게하면 호출자가 필요하지 않은 경우 호출자가 참조 계산을하도록 강요하지 않습니다. (호출자는 공유 의미를 원할 경우 unique_ptr에서 shared_ptr으로 소유권을 이전 할 수 있습니다.)

+0

그래, 작곡 방식은 다소 추한 것입니다 ... 클래스를 "들쭉날쭉하게"만들면 공간 문제를 해결할 수 있지만 ...추한. 응답 주셔서 감사합니다! – IdeaHat