首页 > 解决方案 > 如何安全地从内存中清除使用 new 关键字创建的对象(带有属性)?

问题描述

据我所知,每个“新”调用都需要对该对象进行相应的“删除”调用。那么这真的正确吗?:

using namespace std;

class Box {
   public:
      double length;
      char letters_in_box[80];
};

int main() {
   Box *b = new Box;
   b->length = 2.0;
   b->letters_in_box = "Hello world";

   //Some code with b

   delete b;

   return 0;
}

与“length”双精度和“letters_in_box”数组相关的内存是否被清除?

标签: c++classnew-operatordelete-operator

解决方案


是的。当您删除b它时,它也会删除letters_in_box数组。

但是,对于您,b->letters_in_box = "Hello world";您将收到一个编译错误:“错误 C3863:数组类型 'char [80]' 不可分配”

#include <memory> // For 'memcpy_s' (since C11)

class Box
{
public:
    double length;
    char letters_in_box[80];
};

int main()
{
    Box* b = new Box;

    b->length = 2.0;
    // b->letters_in_box = "Hello world"; ** Compile Error C3863: array type 'char [80]' is not assignable **
    memcpy_s(b->letters_in_box, sizeof(b->letters_in_box), "Hello world", sizeof("Hello world"));

    // Some code with b

    delete b;
}

现代 C++

newsmart pointers更好的做法,例如,在出现异常的情况下,您不必为 delete 操心:

#include <memory> // For 'std::unique_ptr' and for 'memcpy_s'

class Box
{
public:
    double length;
    char letters_in_box[80];
};

constexpr char my_text[] = "Hello world"; 

int main()
{
    auto b = std::make_unique<Box>(); // No need to delete

    b->length = 2.0;
    memcpy_s(b->letters_in_box, sizeof(b->letters_in_box), my_text, sizeof(my_text));

    // Some code with b
}

另外,(而不是 C 数组)我更喜欢使用C++ 数组

#include <array>  // For 'std::array'
#include <memory> // For 'std::unique_ptr' and for 'memcpy_s' 

class Box
{
public:
    double length;
    std::array<char, 80> letters_in_box;
};
   
constexpr char my_text[] = "Hello world";

int main()
{
    auto b = std::make_unique<Box>(); // No need to delete

    b->length = 2.0;
    memcpy_s(&b->letters_in_box, b->letters_in_box.size(), my_text, sizeof(my_text));

    //Some code with b
}

--

最后一条评论:如果没有使用约束char[],我会std::string改用:

#include <string> // For 'std::string'
#include <memory> // For 'std::unique_ptr' 

class Box
{
public:
    double length;
    std::string letters_in_box;
};

int main()
{
    auto b = std::make_unique<Box>(); // No need to delete

    b->length = 2.0;
    b->letters_in_box = "Hello world";

    //Some code with b
}

推荐阅读