추상 기본 클래스 (ABC)의 구체적인 인스턴스에 대한 원시 포인터 벡터의 수명을 수동으로 처리하는 일부 오래된 코드를 다시 작성했습니다. 방법/벡터 <unique_ptr <ABC>>을 가질 수 있습니까?
그래서 벡터의 소유자가 직접 겪은과 벡터의 내용을 삭제 가상 dtor 등 벡터의 소유자가의 요소를 소유하고 있기 때문에했다, 그것은 많은 의미가 변경할 수 있습니다 unique_ptr의 벡터.
슬프게도 이것이 불가능한 것 같습니까? vector<unique_ptr<type>>
가 type
에 대한 정적 dtor을 할 수 있어야하지만 때문에이 경우 유형에 ABC이기 때문에, 즉, 따라서 vector
이 ...
를 컴파일되지 않습니다 아니면 내가 뭔가를 놓친 거지 사용할 수 없습니다?
예 :
struct ABC
{
ABC() = default;
virtual ~ABC() { } // need a vtable entry so that concrete subclasses will be deleted through the base dtor
virtual std::unique_ptr<ABC> Clone() = 0;
virtual void Foo() = 0;
std::vector<std::unique_ptr<ABC>> elements;
};
EDIT2 : 당신이 Base
의 인스턴스 또는 Base
에서 파생 된 형식의 인스턴스를 복사 할 때
#include <iostream>
#include <memory>
#include <vector>
struct ABC
{
virtual ~ABC() { } // need a vtable entry so that concrete subclasses will be deleted through the base dtor
virtual std::unique_ptr<ABC> Clone() = 0;
virtual void Foo() = 0;
std::vector<std::unique_ptr<ABC>> elements;
};
struct Child : ABC
{
std::unique_ptr<ABC> Clone() override { return std::make_unique<Child>(*this); }
void Foo() override { };
};
struct Derived : Child
{
std::unique_ptr<ABC> Clone() override { return std::make_unique<Derived>(*this); }
};
int main()
{
std::unique_ptr<ABC> x;
std::unique_ptr<ABC> c = std::make_unique<Child>();
std::vector<std::unique_ptr<ABC>> elements;
elements.emplace_back(std::make_unique<Derived>());
return 0;
}
확실하지하지만 당신은 문제의 예제 코드에서 같은 이름을 사용하는 경우 그것은 당신이 많은 명확하게 무엇을 요구한다 : 완성도를 위해서 – NathanOliver
기지를 전달할 수 없습니까? 정의하기 바로 전에? –
VS 2015 Upd 3에서 기본적으로 메시지의 기본 세트를 가져 오지 않습니다. Base의 삭제 관리자 (아마도 ABC이기 때문입니다) – Mordachai