与指针向量一起使用的对象向量
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
rateObjectList.reserve(7)
实际上并不分配或构造任何ota__RoomRateType
对象;它只是要求向量扩展其容量足以容纳 7 个物体。您可能需要rateObjectList(7); 如果您知道向量创建时的数字。
rateObjectList.resize(7)
。或者 std::vectorrateObjectList.reserve(7)
doesn't actually allocate or construct anyota__RoomRateType
objects; it simply requests that the vector expand its capacity enough to hold 7 objects.Potentially, you wanted
rateObjectList.resize(7)
. Orstd::vector<ota__RoomRateType> rateObjectList(7);
if you know the number at vector creation time.当然。如果在
rateObjectList
被销毁时有人持有roomRates
,那么任何使用roomRates
中的指针的尝试都可能导致SEG_FAULT
。无论如何,这是一个坏主意。在这种情况下更好
更好的是使用智能指针,例如
boost::shared_ptr
Sure. If someone holds
roomRates
whenrateObjectList
destroyed then any attempt to use a pointer fromroomRates
can causeSEG_FAULT
. That's a bad idea, anyway.This is better in this case
Even better is to use smart-pointers, like
boost::shared_ptr