In which cases should malloc be used, and in which cases new in C++?
Greetings, colleagues! I'm learning C++ and have reached memory management. I think I've figured out that malloc is a function from C, and new is an operator in C++. But in practice, I've run into confusion.
Let's say I want to allocate memory for an object of class `Person`. Here are two ways I understand:
```cpp
#include // for 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_;
};
// Option 1: malloc
Person* p1 = (Person*)malloc(sizeof(Person));
// Option 2: new
Person* p2 =
No answers yet.
Log in to leave an answer