简体   繁体   English

要与指针向量一起使用的对象向量

[英]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: gSoap生成的代理对象指示我应该使用指针向量:

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; rateObjectList.reserve(7)实际上并未分配或构造任何ota__RoomRateType对象; it simply requests that the vector expand its capacity enough to hold 7 objects. 它只要求向量扩展其容量足以容纳7个对象。

Potentially, you wanted rateObjectList.resize(7) . 潜在地,您需要rateObjectList.resize(7) Or std::vector<ota__RoomRateType> rateObjectList(7); 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 . 如果在rateObjectList销毁时有人持有roomRates ,则任何使用roomRates的指针的roomRates都可能导致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 更好的方法是使用智能指针,例如boost::shared_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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