【问题标题】:Why is this trying to find the destructor twice?为什么这试图找到析构函数两次?
【发布时间】:2014-12-12 11:26:51
【问题描述】:

我正在尝试以下代码:

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

【问题讨论】:

  • _GENERATEMPLATE_H_reserved identifier。您还应该检查 GCC 以查看它对代码的作用,以便您可以匹配给定的位置。
  • 我只得到一个对析构函数的不明引用(clang++ 和 g++4.9.1,OS X 10.9)
  • 糟糕!应该使用 GENERALTEMPLATE_H。但是改变它并不会改变错误。
  • @toutnom 您使用的是什么编译器/平台?
  • @toutnom,那么我认为@Snefel 和@AndreyT 是对的! (PS:可以用throw()(或C++11中的noexcept)标记函数,并且仍然可能具有相同的行为,即不超过1个dtor调用。

标签: c++ templates undefined-reference


【解决方案1】:

这很可能与异常安全有关。如果arbitraryFunction 抛出异常,堆栈需要展开,这意味着gInt 需要提前销毁。由于这一切都发生在main 中,不会发生进一步的展开,因此它是否真的需要两次调用析构函数是值得怀疑的......但你观察到的行为并没有完全消失。

【讨论】:

  • 对我来说听起来很合理。
  • @Snefdel,@vsoftco:只是断言你所说的!使用“模板 void absoluteFunction(const M &m) throw();”只导致一个析构函数错误而不是两个。所以,问题肯定与抛出异常有关。谢谢!
  • @toutnom,然后您应该接受 Sneftel 的回答,因为它提供了正确的答案并解决了问题。在您等待好答案之后,这是一个很好的 SO 实践。
猜你喜欢
  • 1970-01-01
  • 2021-11-06
  • 2018-07-06
  • 2020-02-23
  • 2019-09-03
  • 2011-02-07
  • 1970-01-01
相关资源
最近更新 更多