C++ - Dynamic memory allocation and class composition

Hello!

Lately I have wondered how should a composition be implemented when it comes to adding objects within an object. Here's a simple piece of code to demonstrate the use:

1
2
3
X x;
Y y;
x.insert(y);


As you can see, object y will be inserted into object x. But how? This is what I'm wondering. Here's the implementation of class X:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class X{
public:
	/// Constructors & destructors:
	X(void) : _m_opY(nullptr){
	
	}
	~X(void){
		if(_m_opY != nullptr)
			delete _m_opY;
	}
	/// Member functions:
	X& extract(Y const& y){
		delete _m_opY;
		_m_opY = nullptr;
	}
	X& insert(Y const& y){
		_m_opY = new Y(y);
	}
private:
	/// Member data:
	Y* _m_opY;
};


Now, is this a good idea? I've heard that the use of dynamic memory allocation should be avoided whenever possible. Prefer stack, right? Well, if that's the case here, there might some kind of danger when it comes to using this class. Can you guess what the problem is? It's the problem that appears after the object y falls out scope:

1
2
3
4
5
X x;
Y y;
x.insert(y);

// Y goes out scope, x points to a non-existing object if I'd use stack instead of heap. 


So, is the use of heap justified here?
So, is the use of heap justified here?
I depends.
The issue isn't stack vs heap. The issue is whether to copy the data or not.

You can copy the data if it's not too much.
You must not copy the data when the data contains pointer or inheritance is involved.

When it comes to variable size data you do not have a choice but to use dynamic memory allocation.

Y goes out scope, x points to a non-existing object if I'd use stack instead of heap.
In your scenario x goes out of scope as well. Even if not. if line 21 would look like Y _m_opY; you had a copy of y. So no problem

[EDIT]
by the way:
This is a copy anyway: _m_opY = new Y(y);
[/EDIT]
Last edited on
Thanks, coder777. I forgot to specify that object x is supposed to contain object y by reference. That way I can modify object y and see the effects also in object x. Here's an example:

1
2
3
4
5
6
Character bob;
Health health;

bob.insert(health);

health -= 15; // Affects object "bob". 


And here's a little fix (should be correct now):

1
2
3
4
X& insert(Y const& y){
	_m_opY = new Y;
	_m_opY = &y;
}


So, should I use dynamic memory allocation in this case?
Last edited on
And here's a little fix (should be correct now):

No, you're allocating memory and you lose the pointer to it in the next line. That's a classic memory leak.
Drop the first line, it's pointless.

So, should I use dynamic memory allocation in this case?

That depends on whether "health" outlives "bob". As I see it, health should be a member of Character.
Topic archived. No new replies allowed.