gpt4 book ai didi

c++ - 为什么在复制分配期间调用析构函数?

转载 作者:行者123 更新时间:2023-11-28 06:41:46 24 4
gpt4 key购买 nike

我定义了以下两个 C++ 结构,RoomHouse . House包含 std::list<Room> .

我创建了一个 House对象 new .我创建一个新的 Roomnew .我创建了另一个 House对象 new并尝试分配之前的 House到这个。但出于某种原因 House析构函数被调用...为什么?

(然后我也遇到段错误)。

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";

我从来没有看到调试“House assigned”。我看到了:

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)

最佳答案

这是 HouseHouse::operator= 方法返回值的析构函数。但是,您忘记了两个赋值运算符中的 return 语句(通常是 return *this;),因此导致崩溃。正如 Matt McNabb 的评论中所述当然通常你也会返回一个引用,而不是一个拷贝。

关于c++ - 为什么在复制分配期间调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com