C ++编程中的三条规则

时间:2013-12-19 23:58:24

标签: c++

我正在实现一个trie类,并遵循C ++中的三个规则:同时具有非默认的coppy构造函数,赋值运算符和析构函数。然而程序仍然崩溃。代码有什么问题?

class Trie
{
private:
    char ch;
    std::vector<Trie*> children;

public:
    std::string* word;
    static std::size_t nodeCount;
    Trie()
    {
        ch=0;
        word=NULL;
        ++nodeCount;
    };

    Trie(char c)
    {
        ch=c;
        word=NULL;
        ++nodeCount;
    };

    ~Trie()
    {
        cleanup();
        --nodeCount;
    };

    Trie(const Trie& source)
    {
        std::cout<<"hello world!\n";
        ch=source.ch;       
        if (source.word)
            word = new std::string(*(source.word));
        for (int i=0; i<int(source.children.size()); i++)
        {
            Trie* newA=new Trie(*(source.children[i]));
            children.push_back(newA);
        }
    }

    Trie& operator=(const Trie &source)
    {
        cleanup();
        ch=source.ch;       
        if (source.word)
            word = new std::string(*(source.word));
        for (int i=0; i<int(source.children.size()); i++)
        {
            Trie* newA=new Trie(*(source.children[i]));
            children.push_back(newA);
        }
        return *this;
    }
    void cleanup()
    {
        for (int i=0; i<int(children.size()); i++)
        {
            delete children[i];
        }
        if (word)
            delete word;
    }

P / S:这是解构函数的测试函数,代码通过了测试:

TEST(memory)
{
  std::size_t base = Trie::nodeCount;
  // many nodes in the global Boggle trie
  CHECK( base == 0 );
  Trie *trie = new Trie();
  CHECK_EQUAL( base + 1, Trie::nodeCount );
  trie->addWord( "and" );
  CHECK_EQUAL( base + 4, Trie::nodeCount );
  trie->addWord( "ant" );
  CHECK_EQUAL( base + 5, Trie::nodeCount );
  delete trie;
  CHECK_EQUAL( base, Trie::nodeCount );
}

但是代码未通过复制构造函数和赋值测试:

TEST(copyTrie)
{
  Trie trie;
  trie.addWord( "and" );
  trie.addWord( "ant" );
  CHECK_EQUAL( "and", *(trie.next('a')->next('n')->next('d')->word) );
  CHECK_EQUAL( "ant", *(trie.next('a')->next('n')->next('t')->word) );

  Trie copy( trie );
  CHECK_EQUAL( "and", *(copy.next('a')->next('n')->next('d')->word) );
  CHECK_EQUAL( "ant", *(copy.next('a')->next('n')->next('t')->word) );

  copy.addWord( "bee" );
  trie.addWord( "cat" );
}

它完全崩溃了最后一个命令trie.addWord(“cat”)

1 个答案:

答案 0 :(得分:2)

您的cleanup函数不会清空children向量。