我在内存泄漏和字符串方面遇到了一个非常奇怪的问题



当我分配几乎相同的类但有一个成员变量作为字符串而不是整数时,我遇到了内存泄漏问题。

带有字符串的类会提供内存泄漏,但不会给出整数的类。我已经删除了我可以删除的所有内容,但我仍然收到内存泄漏,请帮助。

所以有声读物类给了我内存泄漏,我不知道为什么,因为我没有分配任何东西,但是当我删除字符串成员时,我不再得到内存泄漏,为什么会发生这种情况?

//主要

#include <iostream>
#include "PappersBok.h"
#include "SoundBook.h"
int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    Books *bk[5];
    bk[0] = new SoundBook();
    bk[1] = new PappersBok();
    bk[2] = new PappersBok();
    bk[3] = new PappersBok();
    bk[4] = new PappersBok();
    for (int i = 0; i < 5; i++)
    {
        delete bk[i];
    }

    system("pause");
    return 0;
}

有声读物类 .h 和 .cpp

#ifndef SOUNDBOOK_H
#define SOUNDBOOK_H

#include "books.h"
class SoundBook : public Books
{
private:
    std::string medium;
public:
    SoundBook(std::string title = "?", std::string author = "?", std::string medium = "?");
    ~SoundBook();
    std::string toString() const;
    void setMedium(std::string medium);
};

#endif
//.cpp
#include "SoundBook.h"

SoundBook::SoundBook(std::string title, std::string author, std::string medium)
    :Books(title, author)
{
    this->medium = medium;
}
SoundBook::~SoundBook()
{
}  
std::string SoundBook::toString() const
{
    return ", Medium: " + this->medium;
}

Pappersbok 类 .cpp 和 .h

#ifndef PAPPERSBOK_H
#define PAPPERSBOK_H

#include "books.h"
class PappersBok : public Books
{
private:
    int nrOfPages;
public:
    PappersBok(std::string title = "?", std::string author = "?", int nrOfPages = 0);
    ~PappersBok();
    std::string toString() const;
};
#endif

//。.cpp

#include "PappersBok.h"

PappersBok::PappersBok(std::string title, std::string author, int nrOfPages)
    :Books(title, author)
{
    this->nrOfPages = nrOfPages;
}

PappersBok::~PappersBok()
{
}
std::string PappersBok::toString() const
{
    return ", Number of pages: " + std::to_string(this->nrOfPages);
}

任何关于C++多态性的介绍性文本都会告诉你使用虚拟析构函数

否则,当您在基指针上调用delete时,它无法正常工作。

bk[0]是一个指向SoundBookBooks*,但delete不知道它指向一个SoundBook,所以不能完全摧毁其派生部分的成员。 因此内存泄漏(更广泛地说,程序具有未定义的行为(。

最新更新