我尝试了一些有趣的代码(至少对我来说是这样!)。 这是它。
#include <iostream>
struct myStruct{
int one;
/*Destructor: Program crashes if the below code uncommented*/
/*
~myStruct(){
std::cout<<"des\n";
}
*/
};
struct finalStruct {
int noOfChars;
int noOfStructs;
union {
myStruct *structPtr;
char *charPtr;
}U;
};
int main(){
finalStruct obj;
obj.noOfChars = 2;
obj.noOfStructs = 1;
int bytesToAllocate = sizeof(char)*obj.noOfChars
+ sizeof(myStruct)*obj.noOfStructs;
obj.U.charPtr = new char[bytesToAllocate];
/*Now both the pointers charPtr and structPtr points to same location*/
delete []obj.U.structPtr;
}
我已经为charPtr分配了内存,并使用structPtr删除了它。如果我在myStruct中添加一个析构函数,程序就会崩溃,否则没有问题。
这里到底发生了什么?据我所知,delete[]将调用与new[]中给定的数字相同次数的析构函数。为什么当myStruct中没有析构函数时,程序不会崩溃呢?
char*
进行别名处理是有保证的。 - Lightness Races in Orbitchar
(或unsigned char
)数组访问,但我仍然认为不能通过联合中的这种指针访问。 - Angew is no longer proud of SO