Using non-placement new expression
时间: 2024-04-12 17:27:19 浏览: 19
Non-placement new expression is a way to create objects in C++ without specifying the memory location where the object should be allocated. It is achieved by using the "new" keyword followed by the type name and constructor arguments.
For example, consider a class called "Person" with a constructor that takes a name and age as arguments. We can create a new object of the Person class using non-placement new expression as follows:
```cpp
Person* person = new Person("John Doe", 25);
```
In this example, the "new" keyword dynamically allocates memory for a Person object and calls its constructor with the provided arguments. The expression returns a pointer to the newly created object, which can be stored in a pointer variable (person in this case).
It is important to note that when using non-placement new expression, it is the responsibility of the programmer to manually deallocate the memory allocated using the "delete" keyword when the object is no longer needed. Failing to do so can result in memory leaks.