簡體   English   中英

刪除非模板化類析構函數中的模板化類指針?

[英]Deleting templated class pointers in a non-templated class destructor?

下面的代碼test-templated-destructor.cpp復制了我正在使用的庫的組織。 我正在使用:

$ cat /etc/issue
Ubuntu 14.04.5 LTS \n \l
$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
$ g++ -std=c++14
g++: error: unrecognized command line option ‘-std=c++14’
g++: fatal error: no input files
compilation terminated.
$ g++ -std=c++11
g++: fatal error: no input files
compilation terminated.

有:

  • 基類AA以及從中衍生的類BBCC ;
  • 抽象類AAInstancer和類從它派生AAInstancerTemplated這是模板
  • AAHandler ,具有模板化函數addTemplatedObject ,該函數在類的map屬性中存儲指向new AAInstancerTemplated<T>()對象的AAInstancer*指針
  • main() ,實例化AAHandler對象,然后添加.addTemplatedObject<BB>("BB"); 呼吁

如果我對此運行valgrind ,則會報告:

==21000== 43 (16 direct, 27 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==21000==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21000==    by 0x40141B: void AAHandler::addTemplatedObject<BB>(std::string) (test-templated-destructor.cpp:64)
==21000==    by 0x40113E: main (test-templated-destructor.cpp:82)

我認為問題在於我們在addTemplatedObject()使用了new ,因此我們應該在程序退出時相應地將其最新刪除-但這沒有完成,因此是泄漏的原因。

因此,我想編寫一個遍歷instancers映射的迭代器,並在AAHandler的AAHandler器中delete這些指針,但是我不能:

  • 如果我寫:
  ~AAHandler() {
    cout << "  (running AAHandler destructor)" << endl;
    map<string, AAInstancer*>::iterator it;
    for ( it = instancers.begin(); it != instancers.end(); it++ ) {
      delete it->second;
    }
  }

...然后我進行編譯:

$ g++ -g -Wall test-templated-destructor.cpp -o test-templated-destructor.exe
test-templated-destructor.cpp: In destructor ‘AAHandler::~AAHandler()’:
test-templated-destructor.cpp:60:18: warning: deleting object of abstract class type ‘AAInstancer’ which has non-virtual destructor will cause undefined behaviour [-Wdelete-non-virtual-dtor]
       delete it->second;
                  ^

...聽起來AAInstancer沒有定義析構函數,因此編譯器可能自動添加為非虛擬的,從而導致此警告(盡管通過valgrind運行此命令將顯示不再檢測到泄漏)。

  • 如果我寫:
  template <class T>
  ~AAHandler() {
      cout << "  (running AAHandler destructor)" << endl;
      map<string, AAInstancer*>::iterator it;
      for ( it = instancers.begin(); it != instancers.end(); it++ ) {
        delete (AAInstancerTemplated<T>*)it->second;
      }
    }

...希望如果我們使用一些模板調用addTemplatedObject時會調用此析構函數(無論如何都不會),編譯會失敗:

$ g++ -g -Wall test-templated-destructor.cpp -o test-templated-destructor.exe && ./test-templated-destructor.exe
test-templated-destructor.cpp:57:14: error: destructor ‘AAHandler::~AAHandler()’ declared as member template
   ~AAHandler() {
              ^

……這也很有意義: AAHandler是一個非模板類,因此它的析構函數也不應被模板化。

那么,是否有可能為AAHandler編寫一個析構AAHandler ,該析構函數將deleteinstancers所有new指針,而不管它們使用哪個模板實例化-只需對現有代碼進行最少(或最好,無)更改?

test-templated-destructor.cpp

// g++ -g -Wall test-templated-destructor.cpp -o test-templated-destructor.exe && ./test-templated-destructor.exe
// valgrind --leak-check=yes ./test-templated-destructor.exe

#include <iostream>
#include <map>
using namespace std;

class AA {
public:
  string myname;
  AA() {
    myname = "";
    cout << "  AA instantiated\n";
  }
};


class BB : public AA {
public:
  string mystuff;
  BB() {
    mystuff = "";
    cout << "  BB instantiated\n";
  }
};

class CC : public AA {
public:
  string mythings;
  CC() {
    mythings = "";
    cout << "  CC instantiated\n";
  }
};

class AAInstancer
{
public:
    virtual AA* createInstance() = 0;
    string tagName;
};

template <class T>
class AAInstancerTemplated: public AAInstancer
{
public:
    AA* createInstance() {
        return new T();
    }
};


class AAHandler
{
public:
    ~AAHandler() { }
    AAHandler() { }
    static map<string, AAInstancer*> instancers;

    template <class T>
    static void addTemplatedObject(string tagName) {
        AAInstancer* instancer = new AAInstancerTemplated<T>();
        instancer->tagName = tagName;
        instancers[tagName] = instancer;
    }

  AAHandler* get() {
    if(singleton == NULL)
      singleton = new AAHandler();
    return singleton;
  }
private:
    static AAHandler* singleton;
};
map<string, AAInstancer*> AAHandler::instancers;



int main()
{
  AAHandler aah;
  aah.addTemplatedObject<BB>("BB");

  cout << "Address of aah: " << static_cast<void*>(&aah) << endl;
  return 0;
}

AAInstancer需要一個虛擬析構函數。 如果不需要主體,則可以默認。

virtual ~AAInstancer() = default;

使用std::unique_ptr<AAInstancer>

map<string, std::unique_ptr<AAInstancer>>

作為成員,而不是自己管理內存。

好的,終於有了可以在c++11下編譯良好且不會泄漏的東西。 valgrind報告:

$ valgrind --leak-check=yes ./test-templated-destructor.exe==22888== Memcheck, a memory error detector
==22888== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==22888== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==22888== Command: ./test-templated-destructor.exe
==22888== 
Address of aah: 0xffefffb3f
  (running AAHandler destructor)
  ~AAInstancerTemplated <2BB> here; tref: 0x5a200b0
    ~AAInstancer here
  ~AAInstancerTemplated <2CC> here; tref: 0x5a201e0
    ~AAInstancer here
==22888== 
==22888== HEAP SUMMARY:
==22888==     in use at exit: 0 bytes in 0 blocks
==22888==   total heap usage: 6 allocs, 6 frees, 198 bytes allocated
==22888== 
==22888== All heap blocks were freed -- no leaks are possible
==22888== 
==22888== For counts of detected and suppressed errors, rerun with: -v
==22888== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

是的,沒有泄漏-我喜歡:)

該方法有點經典:使AAInstancerTemplated保留對通過new實例化的AAInstancerTemplated的引用(此處為tref ),然后為其創建析構函數(針對AAInstancerTemplated ),以delete該引用。

請注意,即使在AAHandler ,我們AAInstancer*instancers化器中存儲通用指針AAInstancer* ,而我們實例化模板化對象( new AAInstancerTemplated<T>(); )時–現在,通過此組織,當我們delete it->second類型AAInstancer* ,將調用正確的模板化析構函數。

固定的test-templated-destructor.cpp

// g++ -g -std=c++11 test-templated-destructor.cpp -o test-templated-destructor.exe && ./test-templated-destructor.exe
// valgrind --leak-check=yes ./test-templated-destructor.exe

#include <iostream>
#include <map>
#include <typeinfo>
#include <functional> // note: uses std::function, which is c++11 feature

using namespace std;

class AA {
public:
  string myname;
  AA() {
    myname = "";
    cout << "  AA instantiated\n";
  }
};


class BB : public AA {
public:
  string mystuff;
  BB() {
    mystuff = "";
    cout << "  BB instantiated\n";
  }
};

class CC : public AA {
public:
  string mythings;
  CC() {
    mythings = "";
    cout << "  CC instantiated\n";
  }
};

class AAInstancer
{
public:
  virtual ~AAInstancer() {
    cout << "    ~AAInstancer here" << endl;
  }
  virtual AA* createInstance() = 0;
  string tagName;
};

template <class T>
class AAInstancerTemplated: public AAInstancer
{
public:
  T* tref;
  AA* createInstance() {
    if (tref) delete tref;
    tref = new T();
    return tref;
  }
  ~AAInstancerTemplated() {
    cout << "  ~AAInstancerTemplated <" << typeid(T).name() << "> here; tref: " << static_cast<void*>(&tref) << endl;
    if (tref) delete tref;
  }
};


class AAHandler
{
public:
  ~AAHandler() {
    cout << "  (running AAHandler destructor)" << endl;
    typedef typename map<string, AAInstancer*>::iterator instIterator;
    for ( instIterator it = instancers.begin(); it != instancers.end(); it++ ) {
      delete it->second;
    }
  }
  AAHandler() { }
  static map<string, AAInstancer*> instancers;

  template <class T>
  static void addTemplatedObject(string tagName) {
    AAInstancer* instancer = new AAInstancerTemplated<T>();
    instancer->tagName = tagName;
    instancers[tagName] = instancer;
  }

  AAHandler* get() {
    if(singleton == NULL)
      singleton = new AAHandler();
    return singleton;
  }
private:
  static AAHandler* singleton;
};
map<string, AAInstancer*> AAHandler::instancers;

int main()
{
  AAHandler aah;
  aah.addTemplatedObject<BB>("BB");
  aah.addTemplatedObject<CC>("CC");

  cout << "Address of aah: " << static_cast<void*>(&aah) << endl;
  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM