类析构函数

时间:2016-12-29 23:25:59

标签: c++

我在c ++中使用dll,第二次调用函数时出现此错误:

调试断言失败表达式:_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)

我做了一些研究,这似乎发生在我delete一个我没有new

的对象时

以下是我认为失败的代码

class tFont
{
public:
    tFont(char chars[], __int64 cods[], int count);
    ~tFont();


    int fontCount = 0;
    char* characters = NULL;
    long long* codes = NULL;

    std::vector<std::pair<char,long long>> exceptions;


    char getCharacter(long long code);


};

tFont::tFont(char chars[], long long cods[], int count)
{
    characters = new char[count];
    codes = new long long[count];
    fontCount = count;

    for (int i = 0; i < count; i++)
    {
        characters[i] = chars[i];
        codes[i] = cods[i];
    }


}


tFont::~tFont()
{

        delete[] characters;
        delete[] codes;
}

Visual Studio在错误发生后停在delete[] characters;

我没有运气就试了这个

if (characters != NULL)
{
    delete[] characters;
}
if (codes != NULL)
{
    delete[] codes;
}

我只创建这个类的一个实例作为静态对象

tFont* getCapFont()
{
    static tFont *capFont = NULL;

    if (capFont == NULL)
    {
        char characters[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        long long codes[] = { 241136, 441, 183861, 102321, 45836, 5955, 19305, 7871, 220321, 102286 };
        int fontCount = 10;

        capFont = new tFont(characters, codes, fontCount);
        pair<char, long long> e;
        e.first = '0';
        e.second = 24045;

        capFont->exceptions.push_back(e);
    }

    return capFont;
} 

为什么即使我从未做过delete capFont

,也会调用析构函数

谢谢!

Edit2 :我做了&#39; jarmod&#39;表示错误发生的时刻是此函数结束的时间

void analysis::singleLineTextReader(tImage img, char result[], tFont font)

我说第二次调用函数时发生了这种情况,当singleLineTextReader结束时调用其参数font的析构函数是可能的吗?哪个是上面描述的静态对象

1 个答案:

答案 0 :(得分:2)

void analysis::singleLineTextReader(tImage img, char result[], tFont font)

请注意,font按值传递。您没有传递指针。您没有传递对它的引用。您传递

因此,您正在传递singleLineTextReader一个 tFont对象,该对象是通过构建您传递给它的副本创建的。当副本的析构函数运行时,它会销毁基础对象的成员。当你再次这样做时,你正在摧毁已经被摧毁的物体。

遵循3/5/0的规则。不需要时不要复制对象。

除非您别无选择,否则请勿使用new / new[]。在这里你可以使用各种其他东西,比如矢量。