다음 두 개의 C++ 구조체, Room
및 House
을 정의했습니다. House
에는 std::list<Room>
이 포함되어 있습니다.복사 할당 중에 소멸자가 호출되는 이유는 무엇입니까?
new
으로 House
개체를 만듭니다. 새 Room
을 new
으로 만듭니다. new
으로 다른 House
개체를 만들고 이전 House
을이 개체에 할당하려고 시도합니다. 그러나 어떤 이유로 든 House
소멸자가 호출됩니다 ... 왜?
(그런 다음 seg 오류가 발생 함).
struct Room
{
Room()
: pString(0)
{
std::cout << "Room ctor [" << std::hex << this << "]\n";
}
Room(const Room& other)
{
std::cout << "Room COPY ctor [" << std::hex << this << "] other: " << std::hex << &other << "]\n";
if(other.pString)
{
if(pString)
delete pString;
pString = strdup(other.pString);
}
}
Room operator=(const Room& other)
{
std::cout << "Room ASSIGNMENT operator [" << std::hex << this << "] other: " << std::hex << &other << "]\n";
if(this != &other)
{
if(other.pString)
{
if(pString)
delete pString;
pString = strdup(other.pString);
}
}
}
~Room()
{
std::cout << "Room dtor [" << std::hex << this << "]\n";
if(pString)
delete pString;
}
char * pString;
};
/// House struct ////////////////////////////
struct House
{
House()
{
std::cout << "House ctor [" << std::hex << this << "]\n";
}
House(const House& other)
{
std::cout << "House COPY ctor [" << std::hex << this << "] other: " << std::hex << &other << "]\n";
roomlist = other.roomlist;
}
House operator=(const House& other)
{
std::cout << "House ASSIGNMENT ctor [" << std::hex << this << "] other: " << std::hex << &other << "]\n";
if(this != &other)
{
roomlist = other.roomlist;
}
}
~House()
{
std::cout << "House dtor [" << std::hex << this << "]\n";
}
std::list<Room> roomlist;
};
이를 테스트하는 코드는 다음과 같습니다 :
House * pCurHouse = new House;
Room * pIkeaRm = new Room;
pIkeaRm->pString = strdup("IKEA ROOM");
std::cout << "Room created\n\n\n";
pCurHouse->roomlist.push_back(*pIkeaRm);
House * pOtherHouse = new House;
std::cout << "assigning current house to this house... \n";
*pOtherHouse = *pCurHouse;
std::cout << "House assigned. \n\n\n";
내가 디버그를 볼 수 없습니다 "하우스 할당". 대신 참조 :
assigning current house to this house...
House ASSIGNMENT operator [0x20753a0] other: 0x2075210]
Room COPY constructor [0x2075400] other: 0x2075310]
House destructor [0x7fff36a7a6a0] //// which House object is that????
Room destructor [0x402580]
Segmentation fault (core dumped)
룸 복사 생성자는'pString'을 초기화하지 않고 나중에 삭제합니다 (초기화되지 않은 포인터에서는 널 검사가 쓸모 없습니다). 정의되지 않은 동작이 이어집니다. – SleuthEye
'new'를 너무 많이 사용하는 특별한 이유가 있습니까? 'new '를 사용하는 이유가 있습니까? –
@Benjamin, 결국 나는 다른 교실에 'House'멤버를 넣을 것이고, 어떤 때는 House '멤버를 다른 House로 교체 할 수 있기를 원합니다. 나는 포인터가 유용 할 수 있다고 생각했다. 더 좋은 방법이 있니? – patchwork