开发者

Default destructor freeing an array member of a class, c++

开发者 https://www.devze.com 2023-03-31 16:20 出处:网络
Say I have the following classes: class A {}; Class C { private: A a[10]; }; int main() { C c; } Will this code cause a memory leak? As in, will the default destruct开发者_运维问答or that the com

Say I have the following classes:

class A {};

Class C {
private:
    A a[10];
};

int main() {
    C c;
}

Will this code cause a memory leak? As in, will the default destruct开发者_运维问答or that the compiler will define for the C class free the memory of the array of A objects successfully?

I tried to check myself but I couldn't figure out how to run valgrind on OSX 10.7...


This will not leak. If you want to make sure, put a debug statement in the destructor of A.

EDIT: simple example...

#include <iostream>

class A 
{
public:
  A() { std::cout << "A::A()" << std::endl; }
  ~A() { std::cout << "A::~A()" << std::endl; }
};

Class C {
private:
    A a[10];
};

int main() {
    C c;
}

Now compiling and running the above example, should produce 10 instances of the first debug statement and 10 instances of the second debug statement. The last 10 statements are produced when the 10 instances of A are destroyed (which is done automatically for you - hence the term automatic storage, when they go out of scope - in this case, that is when the instance of C [which owns them] goes out of scope [at the end of main].)


No it won't cause a memory leak. The classes doesn't use new at all so the there is no memory dynamically allocated in the heap.


Memory leak issue arises only for dynamic memory allocation. For automatically allocated memory (usually on stack or data segment) there is never a memory leak.

0

精彩评论

暂无评论...
验证码 换一张
取 消