C++ 为什么 new 关键字有效而 malloc 无效?
C++ why does new keyword works and malloc does not?
我正在学习指针和结构,我 运行 进入这个对我来说很难理解的问题。
我创建了这个简单的程序用于测试目的:
#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 关键字,但我想稍微试验一下。
new
使用 class' 构造函数初始化分配的内存(在本例中是隐式的)。
malloc
不执行初始化,它只是分配一部分内存。读取未初始化的内存将有未定义的行为。
以下是您的第二个示例的工作原理。通常,这不是使用 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);
}
对于malloc,你分配了一块内存,但没有创建对象。 testStructure
构造函数未被调用。
您可以在内存区域调用构造函数,放置位置为 new:
char* ptr = malloc(sizeof testStructure);
testStruct = new(ptr) testStructure;
但这很难阅读、令人困惑、难以维护并且充满风险。比如你需要
- free() 不删除 ptr
- 您需要类似地显式调用析构函数。
所以,不推荐。
我正在学习指针和结构,我 运行 进入这个对我来说很难理解的问题。 我创建了这个简单的程序用于测试目的:
#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 关键字,但我想稍微试验一下。
new
使用 class' 构造函数初始化分配的内存(在本例中是隐式的)。
malloc
不执行初始化,它只是分配一部分内存。读取未初始化的内存将有未定义的行为。
以下是您的第二个示例的工作原理。通常,这不是使用 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);
}
对于malloc,你分配了一块内存,但没有创建对象。 testStructure
构造函数未被调用。
您可以在内存区域调用构造函数,放置位置为 new:
char* ptr = malloc(sizeof testStructure);
testStruct = new(ptr) testStructure;
但这很难阅读、令人困惑、难以维护并且充满风险。比如你需要
- free() 不删除 ptr
- 您需要类似地显式调用析构函数。
所以,不推荐。