繁体   English   中英

为什么为模板实例声明运行时多态性会导致链接器错误?

[英]Why does declaring runtime polymorphism for template instantiations result in linker error?

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

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(){...}

(尽管最后两次更改不会影响结果,即:如果我在子类中的实际实现之前错过了虚函数,则会收到相同的错误)

我得到:

/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)

为什么呢

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

N3376 12.4 / 9的相关报价

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

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

AnyThreadImplementation::~AnyThreadImplementation() {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM