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

时间:2014-09-14 22:22:57

标签: c++

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

我使用House创建了一个new对象。我使用Room创建了一个新的new。我使用House创建了另一个new对象,并尝试将之前的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";

我从未看到调试&#34; House已分配&#34;。我明白了:

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)

1 个答案:

答案 0 :(得分:1)

这是House House::operator=方法的返回值的析构函数。然而,您忘记了两个赋值运算符中的返回语句(通常是return *this;),因此崩溃了。正如Matt McNabb的评论中所指出的那样,当然通常也会返回引用,而不是副本。