Search code examples
c++gsoapstd

vector of objects to use with a vector of pointers


The proxy objects generated by gSoap indicate that I should use a vector of pointers:

class SOAP_CMAC ota__RoomStayTypeRoomRates
{
public:
    std::vector<class ota__RoomRateType * >RoomRate;
    //....
};

Rather than using:

vector.push_back(new Object());

and then having to delete the objects, I thought I might create a vector of objects and then use the address of those objects as they will be destroyed when the vector goes out of scope, thereby avoiding memory leaks:

OTARoomRates roomRates;

std::vector<ota__RoomRateType> rateObjectList;

rateObjectList.reserve(7);
for (int i = 0; i < 7; i++)
{
    rateObjectList[i].RoomTypeCode = &roomTypeCode;
    rateObjectList[i].RatePlanID = &ratePlanID;
    //...
    roomRates.RoomRate.push_back(&rateObjectList[i]);
}

I get a segfault. I suppose it's a bad idea. Can you explain why?


Solution

  • rateObjectList.reserve(7) doesn't actually allocate or construct any ota__RoomRateType objects; it simply requests that the vector expand its capacity enough to hold 7 objects.

    Potentially, you wanted rateObjectList.resize(7). Or std::vector<ota__RoomRateType> rateObjectList(7); if you know the number at vector creation time.