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

发布于 2025-01-03 17:40:40 字数 707 浏览 0 评论 0原文

gSoap 生成的代理对象表明我应该使用指针向量:

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

而不是使用:

vector.push_back(new Object());

然后必须删除对象,我想我可以创建一个对象向量,然后使用这些对象的地址,因为它们将被销毁当向量超出范围时,从而避免内存泄漏:

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]);
}

我遇到了段错误。我想这是个坏主意。你能解释一下为什么吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏了南城 2025-01-10 17:40:40

rateObjectList.reserve(7) 实际上并不分配或构造任何 ota__RoomRateType 对象;它只是要求向量扩展其容量足以容纳 7 个物体。

您可能需要 rateObjectList.resize(7)。或者 std::vectorrateObjectList(7); 如果您知道向量创建时的数字。

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.

爱的十字路口 2025-01-10 17:40:40

你能解释一下为什么吗?

当然。如果在 rateObjectList 被销毁时有人持有 roomRates,那么任何使用 roomRates 中的指针的尝试都可能导致 SEG_FAULT。无论如何,这是一个坏主意。

在这种情况下更好

vector.push_back(new Object());

更好的是使用智能指针,例如 boost::shared_ptr

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文