I've just run two valgrind tests on the following pieces of code:
First run:
class Foo
{
public:
Foo(){}
virtual ~Foo(){}
};
class Bar: public Foo
{
public:
Bar(){}
virtual ~Bar(){}
};
int main(int argc, char** argv)
{
std::auto_ptr<Foo>arr[3];
std::auto_ptr<Foo> one(new Bar());
std::auto_ptr<Foo> two(new Bar());
std::auto_ptr<Foo> three(new Bar());
arr[0] = one;
arr[1] = two;
arr[2] = three;
return 0;
}
Second run:
class Foo
{
public:
Foo(){}
virtual ~Foo(){}
};
class Bar: public Foo
{
public:
Bar(){}
virtual ~Bar(){}
};
int main(int argc, char** argv)
{
std::auto_ptr<Foo> one(new Bar());
return 0;
}
While Valgrind indeed shows possible memory leaks in both cases, the warnings it displays are exactly the same (same number of warnings, same text of warnings, same stack) for both of them, pointing somewhere outside of my code to linux .so files. Thus, we can assume that the way you use the array of auto_ptr
is fine. However, as it is stated in comments, since C++0x (which is the current C++ standard), auto_ptr
is considered deprecated because of it's weird copy behaviour (you can find more info, for example, in this article). It is advised to use std::unique_ptr
instead.
Now, if you are having some extra memory leaks in your code, then most likely it happens because of your own classes. Unfortunately, you haven't included them into the question, so we can't tell. In such a case, you should check your classes' constructors and destructors for memory leaks, or at least show us your classes. Another cause may be the typo in the array index that you have in the code (pbase[3]
, which is out of bonds).