简体   繁体   中英

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?

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.

Can you explain why?

Sure. If someone holds roomRates when rateObjectList destroyed then any attempt to use a pointer from roomRates can cause SEG_FAULT . That's a bad idea, anyway.

This is better in this case

vector.push_back(new Object());

Even better is to use smart-pointers, like boost::shared_ptr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM