0

我有一个完美的工作代码:

template <typename ...Ts>
class ThreadImplementation {
    ...
    void launch(){...}
    ~ThreadImplementation(){...}
};
...
ThreadImplementation<Ts...> *t = new ThreadImplementation<Ts...>(debugName,func,args...);
...
// std::vector< std::unique_ptr< ThreadImplementation<> > >  thread_107_allThreads;
thread_107_allThreads.emplace_back(t);
...

其中 thread_107_allThreads 现在只存储没有模板参数的那些,因此 ThreadImplementation<> 在声明中

现在,如果我首先添加

class AnyThreadImplementation {
    public:
    virtual void launch() = 0;
    virtual ~AnyThreadImplementation() = 0;
};

并仅进行以下 3 项更改(不进行强制转换,不更改使用,也不进行测试):

class ThreadImplementation : public AnyThreadImplementation {

    virtual void launch(){...}

    virtual ~ThreadImplementation(){...}

(尽管最后 2 个更改不会影响结果,即:如果我错过了子类中实际实现前面的虚拟,我会得到同样的错误)

我得到:

/tmp/test-fuPonc.o: In function `_ZN20ThreadImplementationIJEEC2EPKcPFvvE':
test.cpp:(.text._ZN20ThreadImplementationIJEEC2EPKcPFvvE[_ZN20ThreadImplementationIJEEC2EPKcPFvvE]+0xbb): undefined reference to `AnyThreadImplementation::~AnyThreadImplementation()'
/tmp/test-fuPonc.o: In function `_ZN20ThreadImplementationIJEED2Ev':
test.cpp:(.text._ZN20ThreadImplementationIJEED2Ev[_ZN20ThreadImplementationIJEED2Ev]+0x233): undefined reference to `AnyThreadImplementation::~AnyThreadImplementation()'
test.cpp:(.text._ZN20ThreadImplementationIJEED2Ev[_ZN20ThreadImplementationIJEED2Ev]+0x267): undefined reference to `AnyThreadImplementation::~AnyThreadImplementation()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

为什么 ?

4

1 回答 1

1

也应该定义纯虚拟析构函数。

来自 N3376 12.4/9 的相关报价

析构函数可以声明为虚拟或纯虚拟;如果在程序中创建了该类或任何派生类的任何对象,则应定义析构函数。

class AnyThreadImplementation {
    public:
    virtual void launch() = 0;
    virtual ~AnyThreadImplementation() = 0;
};

AnyThreadImplementation::~AnyThreadImplementation() {}
于 2013-06-05T06:15:20.407 回答