C++初学者删除代码

标签 c++ delete-operator

我试图动态地为堆分配内存,然后删除分配的内存。以下是给我带来困难的代码:

// String.cpp
#include "String.h"

String::String() {}

String::String(char* source)
{
 this->Size = this->GetSize(source);
 this->CharArray = new char[this->Size + 1];
 int i = 0;
 for (; i < this->Size; i++) this->CharArray[i] = source[i];
     this->CharArray[i] = '\0';
}

int String::GetSize(const char * source)
{
 int i = 0;
        for (; source[i] != '\0'; i++);
        return i;
}

String::~String()
{
 delete[] this->CharArray;
}

这是编译器尝试删除 CharArray 时出现的错误:

0xC0000005: Access violation reading location 0xccccccc0.

这是堆栈中的最后一次调用:

msvcr100d.dll!operator delete(void * pUserData) Line 52 + 0x3 bytes C++

我相当确定这段代码中存在错误,但会为您提供所需的任何其他信息。哦,是的,使用 VS 2010 for XP。

编辑:这是我的 String.h

// String.h - string class
#pragma once

#define NOT_FOUND -1

class String
{
public:
    String();
    String(char* source);
    static int GetSize(const char * source);
    int Find(const char* aChar, int startPosition = 0);
    ~String();
private:
    char* CharArray;
    int Size;
};

最佳答案

改变你的默认构造函数;鉴于您遇到的错误,删除调用正在尝试删除从未初始化的指针。

String::String() : Size(0), CharArray(NULL) {}

此外,请注意“复制构造函数”。您可能希望将其设为私有(private),只是为了确保您不会隐式触发它。 (如果您不打算调用它,则不需要实现它,只需将函数原型(prototype)粘贴到您的类定义中即可。)也可以类似地“禁用”赋值运算符。

class String
{
   // other stuff

private:
    String(String&);
    String& operator=(String&);
};

这个添加符合“三原则”,即如果任何类需要析构函数、复制构造函数或赋值运算符,它可能需要所有这三个。

编辑:参见http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

关于C++初学者删除代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726079/

相关文章:

c++ - 使用指向对象的指针进行析构

c++ - C++17 标准对 nullptr 调用 delete 有何规定?

c++ - 使用 CMake 在可执行文件中嵌入二进制数据

c++ - Windows中如何取消 'system key down'状态

c++ - PhysX 地形 - Heightfield 与 TriangleMesh

c++ - 如果内存块被手动覆盖,如何删除结构数组

c++ - C++ 中的 delete vs delete[] 运算符

时间:2019-03-09 标签:c++multicastfeed

c++ - 我想用两个版本的 libQtCore.a 检查目标代码

c++ - 如何从 std::list 中正确删除指针?