加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么要尝试两次找到析构函数?

发布时间:2020-12-16 03:36:38 所属栏目:百科 来源:网络整理
导读:我正在尝试以下代码: GeneralTemplate.h #ifndef _GENERATEMPLATE_H_#define _GENERATEMPLATE_H_#include iostreamtemplate class Tclass GeneralTemplate{ public: GeneralTemplate(); GeneralTemplate(const GeneralTemplate g); ~GeneralTemplate(); Gen
我正在尝试以下代码:

GeneralTemplate.h

#ifndef _GENERATEMPLATE_H_
#define _GENERATEMPLATE_H_

#include <iostream>

template <class T>
class GeneralTemplate
{
  public:
  GeneralTemplate();
  GeneralTemplate(const GeneralTemplate &g);

  ~GeneralTemplate();

  GeneralTemplate& operator= (GeneralTemplate const& g);

  template <class M>
  void arbitraryFunction(const M &m);
};

#endif

main.cpp中

#include "GeneralTemplate.h"

#include <iostream>

int main()
{
    GeneralTemplate<int> gInt;
    gInt.arbitraryFunction(2.3);
    return 0;
}

请注意,我没有任何类模板的成员函数的实现.但那不是问题.我知道怎么做!如果我尝试编译main.cpp,我应该得到一个链接错误,这就是我得到的.问题是为什么它试图找到两次析构函数(下面的两行错误).

$g++ main.cpp 
/tmp/cckrdPCs.o: In function `main':
main.cpp:(.text+0x13): undefined reference to `GeneralTemplate<int>::GeneralTemplate()'
main.cpp:(.text+0x34): undefined reference to `void GeneralTemplate<int>::arbitraryFunction<double>(double const&)'
main.cpp:(.text+0x45): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
main.cpp:(.text+0x61): undefined reference to `GeneralTemplate<int>::~GeneralTemplate()'
collect2: ld returned 1 exit status

解决方法

它很可能与异常安全有关.如果anyFunction抛出异常,则需要展开堆栈,这意味着需要尽早销毁gInt.由于这一切都发生在main,没有进一步的展开将会发生,它是否真的需要两次调用析构函数是值得怀疑的……但是你所观察到的行为并非完全不在墙上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读