为什么这个虚拟析构函数触发一个未解决的外部? [英] Why does this virtual destructor trigger an unresolved external?

查看:205
本文介绍了为什么这个虚拟析构函数触发一个未解决的外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下方面:



class X
{
X();
virtual〜X();
}

X.cpp:

  #includeXh

X :: X()
{}

尝试构建这个(我使用.dll目标,以避免在缺少的主机上的错误,我使用Visual Studio 2010):


错误1错误LNK2001:未解析的外部符号private:virtual __thiscall X ::〜X(void)(?? 1X @@ EAE @ XZ)


小修改导致成功构建,但是:



Xh:

  class X 
{
inline X ; //现在内联,一切构建
virtual〜X();
}

p> Xh:

  class X 
{
X();
〜X(); //不再虚拟,一切都建立
};

当.dtor为虚拟或.ctor isn'时,链接器中未解析的外部t inlined?



EDIT:



解决方案
不是得到一个未解析的外部>

情况1:



您有构造函数的代码。

因此,它将构造函数构建到对象文件中。构造函数需要将析构函数的地址放入虚拟表中,因为它无法找到它。无法构建构造函数。



情境2:(inline constructor) / h3>

编译器决定不需要构建构造函数(因为它将被内联)。

因此,它不会植入任何代码,因此不需要析构函数的地址。



如果你实现X类型的对象,它会再次抱怨。



< h3>情境3:(非虚拟析构函数)



您不需要析构函数的地址构建构造函数。

不会抱怨。



如果您实例化X类型的对象,它会报错。


Consider the following:

In X.h:

class X
{
    X();
    virtual ~X();
};

X.cpp:

#include "X.h"

X::X()
{}

Try to build this (I'm using a .dll target to avoid an error on the missing main, and I'm using Visual Studio 2010):

Error 1 error LNK2001: unresolved external symbol "private: virtual __thiscall X::~X(void)" (??1X@@EAE@XZ)

Small modifications result in a successful build, however:

X.h:

class X
{
    inline X(); // Now inlined, and everything builds
    virtual ~X();
};

or

X.h:

class X
{
    X();
    ~X(); // No longer virtual, and everything builds
};

What causes the unresolved external in the linker when the .dtor is virtual or when the .ctor isn't inlined?

EDIT:

Or, perhaps more interestingly, why do I not get an unresolved external if I make the destructor non-virtual, or if I inline the constructor?

解决方案

Situation 1:

You have the code for the constructor.
So it builds the constructor into the object file. The constructor needs the address of the destructor to put into the virtual table because it can not find it the constructor can not be built.

Situation 2: (inline constructor)

The compiler decides it does not need to build the constructor (as it will be inlined).
As such it does not plant any code and therefore does not need the address of the destructor.

If you instanciate an object of type X it will again complain.

Situation 3: (non virtual destructor)

You don't need the address of the destructor to build the constructor.
So it does not complain.

It will complain if you instantiate an object of type X.

这篇关于为什么这个虚拟析构函数触发一个未解决的外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆