Using non-placement new expression
时间: 2024-04-12 11:26:58 浏览: 67
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`.
相关推荐
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)