On 03/03/2014 at 23:00, xxxxxxxx wrote:
Originally posted by xxxxxxxx
Originally posted by xxxxxxxx
Sheeesh. Some days it seems like you can't do even the simplest things correctly.
Welcome, joining the club!
Normally, you would think that the BaseContainer is an instantiated class, a living object, floating around, always accessible, until it is destroyed. So that the order of operations is indifferent.
That's the way it is outside the C4D world.
I have to switch off normal thinking, when programming for C4D. In fact, I try not to think.
Over the last 9 months, I have adopted what I would call an instinct, for the weird C4D SDK world. So I more or less use my intuition, not common sense, when writing plugins.
In my daily work, I am a programmer, I switch back to common sense, and get things done, fast. So, so far C4D plugins is a [time consuming] hobby, but I must admit I like it. And I cannot resist the thought, on a rather philosophical level, that maybe this strange world is the reason that C4D is so darn rock solid. Steady like a mountain.
It has really nothing to do with the Cinema 4D API, though. You are programming with C++, you
are not in a managed an environment such as C# as you are used to. Memory must be managed
by the developer.
This is the reason why BaseContainer::SetContainer() must copy the passed container instead
of storing a reference to it!
------------------------------------------------------------------------------------------------------------------------
For now, let us assume that it would not copy but store the reference (aka pointer to the
container).
1.
void func(BaseContainer& parent) {
BaseContainer child;
parent.SetContainer(1000, child);
}
This results in a crash when the parent container is destroyed.
2.
void func(BaseContainer& parent) {
BaseContainer* child = new BaseContainer;
parent.SetContainer(1000, *child);
}
This results in a memory leak when the parent container is destroyed.
Keep in mind that SetContainer() accepts a BaseContainer& (reference), that is why I
dereference the pointer in the second example. It does take a reference to avoid that
the container is copied twice! (Once the function is called, a second time when the container
is actually stored in the parent container).
Best,
-Niklas