【问题标题】:C++ why does new keyword works and malloc does not?C ++为什么new关键字有效而malloc无效?
【发布时间】:2020-08-28 18:12:21
【问题描述】:

我正在学习指针和结构,但我遇到了这个难以理解的问题。 我创建了这个简单的程序用于测试目的:

#include <iostream>

struct testStructure
{
    int a = 0;
    int b = 0;
    int c = 400;
};

int main()
{
    struct testStructure* testStruct;
    testStruct = new testSctructure;

    std::cout << testStruct->c;

    delete testStruct;
    return 0;
}

上面的程序工作得很好,它打印出值 400。但是当我尝试用 malloc 来做时:

#include <iostream>

struct testStructure
{
    int a = 0;
    int b = 0;
    int c = 400;
};

int main()
{
    struct testStructure* testStruct;
    testStruct = (testStructure*)malloc(sizeof testStructure);

    std::cout << testStruct->c;

    free(testStruct);
    return 0;
}

它给了我这个值: -842150451

为什么? 上述示例是在 Visual Studio 2019 中编写和构建的。

我知道在 C++ 中你几乎应该总是想使用 new 关键字,但我想尝试一下。

【问题讨论】:

标签: c++ pointers malloc new-operator


【解决方案1】:

new 使用类的构造函数初始化分配的内存(在本例中是隐含的)。

malloc 不执行初始化,它只是分配一部分内存。读取未初始化的内存会有未定义的行为。

【讨论】:

    【解决方案2】:

    这是您的第二个示例的工作方式。一般来说,这不是使用 C++ 的推荐方式,但有一些有效的用例。

    #include <cstdlib>
    #include <iostream>
    
    struct testStructure {
        int a = 0;
        int b = 0;
        int c = 400;
    };
    
    int main() {
        auto testStruct_memory = std::malloc(sizeof(testStructure));
    
        // In-place constructor.
        auto testStruct = new(testStruct_memory) testStructure();
    
        std::cout << testStruct->c << "\n";
    
        // In-place destructor.
        testStruct->~testStructure();
    
        std::free(testStruct_memory);
    }
    

    【讨论】:

      【解决方案3】:

      在 malloc 的情况下,您分配了一块内存,但没有创建对象。未调用 testStructure 构造函数。

      您可以在内存区域上调用构造函数,并放置一个新的位置:

      char* ptr = malloc(sizeof testStructure);
      testStruct = new(ptr) testStructure;
      

      但这很难阅读、令人困惑、难以维护并且充满风险。例如,你需要

      • free() 不删除指针
      • 您需要同样显式调用析构函数。

      所以,不推荐。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-09
        • 2011-07-05
        • 2012-01-15
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多