Matze
Matze

Reputation: 553

Why does returning a stack object work?

The golden rules of stack objects say, that a stack object gets deleted as soon as it leaves the scope of the function. But in fact code like this works:

Vec3d Vec3d::operator+(Vec3d const& vec) const{
    return Vec3d((x + vec.getX()), (y + vec.getY()), (z + vec.getZ()));
}

The Object that will be created on invocation is actually in stack and gets returned, and it's usable in the function which invoced the operator. So in fact it should throw an exception when i try to use my Vec3d, because it's definetly out of scope of the method of the overloaded operator. Why does it work? It's propably a kind of inline code, where the allocation gets moved to the function call by the compiler instead of inside the function itseld. Or it's a copy constructor thing, where the stack object gets kinda copied as a new stack object in place of the function call...

I 'm new to c++ and trying to understand how the mechanics of c++ really work, but that's kinda confusing when you started with java :D

Thanks in advance

Upvotes: 0

Views: 94

Answers (1)

merlin2011
merlin2011

Reputation: 75639

You are returning a copy of the object created on the stack, constructed using the copy constructor. You are not returning the original object.

On the other hand, if you tried to return a pointer to the object created on the stack, that would be very broken.

Upvotes: 4

Related Questions