Using non-placement new expression
时间: 2024-04-12 17:26:58 浏览: 111
Python库 | osc-placement-1.5.0.tar.gz
Using a non-placement new expression means creating an object dynamically using the "new" operator without specifying a specific memory location for the object. The new operator will automatically allocate memory for the object and return a pointer to the newly created object.
Here's an example of using a non-placement new expression:
```cpp
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called!" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called!" << std::endl;
}
};
int main() {
MyClass* obj = new MyClass(); // Non-placement new expression
// Use the object...
delete obj; // Deallocate memory and call the destructor
return 0;
}
```
In this example, the non-placement new expression `new MyClass()` is used to dynamically create an object of the class `MyClass`. The `new` operator allocates memory for the object and calls the constructor of `MyClass`. Later, `delete` is used to deallocate the memory and call the destructor of `MyClass`.
阅读全文