内存泄漏和字符串我有一个非常奇怪的问题

Ale*_*lex 0 c++ memory-leaks

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

带有字符串的类会产生内存泄漏,但不会产生整数.我删除了我可以删除的所有内容,但我仍然得到内存泄漏请帮忙.

所以soundbook类给我内存泄漏我不知道为什么因为我已经分配任何东西,但当我删除字符串成员我不再得到内存泄漏为什么会发生这种情况?

//主要

#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;
}
Run Code Online (Sandbox Code Playgroud)

// soundbook类.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;
}
Run Code Online (Sandbox Code Playgroud)

// Pappersbok class .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
Run Code Online (Sandbox Code Playgroud)

//.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);
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 6

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

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

bk[0]Books*指向a SoundBook,但delete知道它指向a SoundBook,因此无法完全破坏其派生部分的成员.因此内存泄漏(更广泛地说,程序具有未定义的行为).