在使用 Stroustrup 示例中的联合体中放置 new 的问题可以通过以下解决方法:
- 使用指针进行动态内存分配:在联合体中声明一个指针,并在需要使用 new 进行内存分配时,将指针指向新分配的内存。
union MyUnion {
int i;
float f;
char* str;
};
int main() {
MyUnion u;
u.str = new char[10]; // 使用 new 分配内存
strcpy(u.str, "Hello");
std::cout << u.str << std::endl;
delete[] u.str; // 释放内存
return 0;
}
- 使用析构函数进行内存释放:在联合体中声明一个包含析构函数的类,并在析构函数中进行内存释放。
union MyUnion {
int i;
float f;
~MyUnion() {
if (str != nullptr) {
delete[] str;
}
}
char* str;
};
int main() {
MyUnion u;
u.str = new char[10]; // 使用 new 分配内存
strcpy(u.str, "Hello");
std::cout << u.str << std::endl;
return 0;
}
在这两种方法中,我们需要注意内存管理的问题。使用指针进行动态内存分配时,需要手动释放内存,否则可能导致内存泄漏。使用析构函数进行内存释放时,需要确保在联合体不再使用时调用析构函数释放内存。