destructor call at end of scope existence

May 6, 2014 at 9:28am
I am learning about desctructors and scope to avoid memory leaks.
Last edited on May 6, 2014 at 9:53am
May 6, 2014 at 9:43am
Does this example have a memory leak?
Last edited on May 6, 2014 at 9:59am
May 6, 2014 at 9:49am
Undefined behaviour.

What is the value of a.val after line 15? Unknown, undefined, uninitialized.

It just looks like that the different instances of 'a' on different calls of f() happen to occupy the same memory location. The destructor is called, but the default destructor does nothing that you could see (at least on your platform).
May 6, 2014 at 9:57am
Thanks keskiverto. Yes, I forgot to initialize val in the constructor. Sorry about that.
So I added the initialization for value. Does this example have a memory leak?:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class A
{
	private:
		int val;
	public:
		A() : val(0) { }
		void setVal(int v) { val = v; }
		void incVal() { val++; }
		int getVal() { return val; }
};

int main()
{
	for (int i=0; i<3; i++)
	{
		A a;
		a.incVal();
		std::cout << "val=" << a.getVal() << std::endl;
	// A destructor is automatically called because its scope of existence has finished
	}
}

output:
val=1
val=1
val=1
Last edited on May 6, 2014 at 10:00am
May 6, 2014 at 10:37am
There is nothing to leak, because no dynamic memory is used; only local variables.

Your code is equivalent to:
1
2
3
4
5
6
7
8
9
10
int main()
{
	for (int i=0; i<3; i++)
	{
		int val = 0;
		val++;
		std::cout << "val=" << val << std::endl;
	// scope of existence of 'val' finishes
	}
}
May 6, 2014 at 2:08pm
There is nothing to leak, because no dynamic memory is used

Thank you keskiverto, that makes sense.
Topic archived. No new replies allowed.