【发布时间】:2016-04-19 14:52:13
【问题描述】:
我有一个结构,我在其中使用了 std::deque
class VariantWrapper;
typedef _STL_NAMESPACE_::deque<VariantWrapper> VariantQueue;
struct AttributeValueWrapper
{
AttributeValueWrapper() : bAttributeIsArray(false)
{
pVariantQueue = new VariantQueue;
if(!pVariantQueue)
throw std::bad_alloc();
}
AttributeValueWrapper(const AttributeValueWrapper& a)
{
pVariantQueue = a.TakeOwner();
bAttributeIsArray = a.bAttributeIsArray;
}
AttributeValueWrapper& operator=(AttributeValueWrapper& r)
{
throw std::bad_exception("equal operator not supported in AttributeValueWrapper");
}
VariantQueue* TakeOwner() const
{
VariantQueue *p = pVariantQueue;
pVariantQueue = NULL;
return p;
}
~AttributeValueWrapper()
{
if (pVariantQueue)
{
delete pVariantQueue;
}
}
bool bAttributeIsArray;
mutable VariantQueue *pVariantQueue;};
主要方法:
int main()
{
AttributeValueWrapper attrib;
}
我在 Dr Memory 下运行这段代码(这只是一段代码,项目很大)并且 Dr Memory 显示内存泄漏
pVariantQueue = new VariantQueue 在默认构造函数中
如:
错误 #46:泄漏 8 个直接字节 + 324 个间接字节 replace_operator_new d:\drmemory_package\common\alloc_replace.c(2899): std::_分配 ??:0 std::allocator::allocate ??:0 std::_Wrap_alloc::allocate ??:0 std::_Deque_alloc::_Alloc_proxy ??:0 std::_Deque_alloc::_Deque_alloc ??:0 std::deque::deque ??:0 AttributeValueWrapper::AttributeValueWrapper
请分享您对此问题的看法。
我也尝试过使用std::unique_ptr,但仍然在同一行(同一点)处出现相同的内存泄漏:
struct AttributeValueWrapper
{
AttributeValueWrapper() : bAttributeIsArray(false)
{
pVariantQueue = std::make_unique<VariantQueue>(new VariantQueue);
if(!pVariantQueue)
throw std::bad_alloc();
}
AttributeValueWrapper(const AttributeValueWrapper& a)
{
pVariantQueue = a.TakeOwner();
bAttributeIsArray = a.bAttributeIsArray;
}
AttributeValueWrapper& operator=(AttributeValueWrapper& r)
{
throw std::bad_exception("equal operator not supported in AttributeValueWrapper");
}
std::unique_ptr<VariantQueue> TakeOwner() const
{
std::unique_ptr<VariantQueue> p = std::move(pVariantQueue);
pVariantQueue = NULL;
return p;
}
~AttributeValueWrapper()
{
}
bool bAttributeIsArray;
mutable std::unique_ptr<VariantQueue> pVariantQueue;
};
现在出现内存泄漏
pVariantQueue = std::make_unique<VariantQueue>(new VariantQueue);
维奈
【问题讨论】:
-
有什么理由不让出队成为成员变量?您仍然可以使用 std::swap() 有效地移动其内容
-
请分享更多代码,最小的完整示例会很棒。
-
pVariantQueue = std::make_unique<VariantQueue>(new VariantQueue);你确定不想要pVariantQueue = std::make_unique<VariantQueue>();吗?可能您创建了新的VariantQueue,然后在make_unique中调用了复制构造函数?因此 new 分配的内存被泄露了。 -
我尝试将其设为成员变量,但随后出现“分配给双端队列的内存”错误并且应用程序崩溃了。
-
@Satus - 我也试过 pVariantQueue = std::make_unique
();但仍然出现内存泄漏。
标签: c++ memory-leaks