- 定位 new 表达式(placement new):当你想在已分配的内存上构造对象时,会用到定位 new 表达式,此时需要手动调用构造函数。
#include <iostream>
#include <new>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called" << std::endl;
}
};
int main() {
char buffer[sizeof(MyClass)];
MyClass* obj = new (buffer) MyClass();
// 使用完对象后手动调用析构函数
obj->~MyClass();
return 0;
}
- 在联合(union)中:联合中的成员共享相同的内存位置,当你需要在联合中构造一个有构造函数的类型成员时,需要手动调用构造函数。
#include <iostream>
#include <string>
union MyUnion {
int num;
std::string str;
MyUnion() = default;
~MyUnion() {}
};
int main() {
MyUnion u;
new (&u.str) std::string("Hello");
std::cout << u.str << std::endl;
u.str.~basic_string();
return 0;
}