我在内存泄漏和字符串方面遇到了一个非常奇怪的问题
I'm having a really weird issue with memory leaks and strings
当我分配几乎相同的类但有一个成员变量作为字符串而不是整数时,我遇到了内存泄漏问题。
带有字符串的类会提供内存泄漏,但不会给出整数的类。我已经删除了我可以删除的所有内容,但我仍然收到内存泄漏,请帮助。
所以有声读物类给了我内存泄漏,我不知道为什么,因为我没有分配任何东西,但是当我删除字符串成员时,我不再得到内存泄漏,为什么会发生这种情况?
//主要
#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]
是一个指向SoundBook
的Books*
,但delete
不知道它指向一个SoundBook
,所以不能完全摧毁其派生部分的成员。 因此内存泄漏(更广泛地说,程序具有未定义的行为(。
相关文章:
- 我从int x[3]得到的一个非常奇怪的输出;
- 一个非常简单的win32套接字代码,但工作错误
- 超过CPU时间限制:当MPI_Sent一个非常大的int*时
- 无法使用crfsuite的C++ API编译一个非常简单的Tagger示例
- C++中一个非常简单的枚举类错误
- 我在内存泄漏和字符串方面遇到了一个非常奇怪的问题
- 我正在写一个非常简单的字母评分系统,if语句是最有效的吗?
- 我刚刚创建了一个非常快速的素数排序方法.如何改进?
- 在64位系统上创建一个非常大的数组的缺点是什么
- (c++)代码中一个非常奇怪的问题
- 打印出一个非常小的浮点数
- C++:C字符串、指针和一个非常有趣的while循环
- 在 matlab 中编写一个非常基本的 mex 函数
- 在C 中编写一个非常简单的事件类
- 如何取一个非常大的数的根
- 在使用Qt Creator创建一个非常简单的项目时,在Qt中遇到"segmentation fault"
- 使用C++计算一个非常大的幂
- 一个非常弱的引用(无法转换为共享)
- 在一个非常简单的程序中检测到内存泄漏.怎么办
- 非虚拟接口?(需要一个非常高性能的低级抽象)