C ++:Coverity报告泄漏特别使用引用和容器 [英] C++ : Coverity reports leaks for peculiar use of references and containers
问题描述
Coverity报告泄漏了以下代码。我想要一些帮助理解错误,并重新编写这段代码是无错误的。
(错误在下面的代码中注释为注释)
Coverity reports leaks for the following code. I would like some help understanding the errors and to re-write this code to be error free. ( The errors are annotated as comments in the code below )
int main()
{
...
B* b = ...
// (1) Coverity: Storage is returned from
// allocation function operator new
// (2) Coverity: Assigning ...
A* a = new A();
// (3) Coverity: noescape: Resource a is not freed
// or pointed-to in add_a_to_b
b->add_a_to_b( *a );
...
// (4) Coverity: Resource leak: Variable a going out
// of scope leaks the storage it points to.
}
class B {
public:
std::vector<A> a_vector;
void add_a_to_b( const A& a )
{
a_vector.push_back( a );
}
- EDIT ---
-- EDIT ---
我有一个关于B :: add_a_to_b函数的特殊问题,这反映了我对引用的不完全理解可能:a_vector存储对A的引用,还是创建传递给add_a_to_b的对象的副本?
I had a particular question about the B::add_a_to_b function, and this reflects my incomplete understanding of references perhaps: Does a_vector store a reference to A or does it create a copy of the object passed to add_a_to_b?
推荐答案
你有一个内存泄漏,因为你调用 new
调用 delete
。此外,没有理由调用 new
或动态分配。您可以自动分配 a
。这同样适用于 b
。
You have a memory leak because you called new
and you don't call delete
. Furthermore, there is no reason for you to call new
or allocate dynamically. You can simply allocate a
automatically. The same applies to b
.
B b;
A a;
...
b.add_a_to_b(a); // b stores a copy of `a`.
这篇关于C ++:Coverity报告泄漏特别使用引用和容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!