在C++中何时使用malloc,何时使用new?
各位同行好!我正在学习C++,学到了内存管理部分。我大致明白malloc是C语言的函数,而new是C++的运算符。但在实践中,我产生了困惑。
假设我想为`Person`类的对象分配内存。以下是我理解的两种方式:
```cpp
#include // 用于malloc
#include
class Person {
public:
Person(const std::string& name) : name_(name) {
std::cout << "Person created: " << name_ << std::endl;
}
~Person() {
std::cout << "Person destroyed: " << name_ << std::endl;
}
void greet() { std::cout << "Hi, I'm " << name_ << std::endl; }
private:
std::string name_;
};
// 方式1:malloc
Person* p1 = (Person*)malloc(sizeof(Person));
// 方式2:new
Person* p2 = new Person("Alice");
```
我发现使用`new`时会自动调用构造函数,而使用`malloc`则需要placement new或类似操作。那释放内存呢?`free(p1)`