[Discuss] OT - C++ operator overloading question.

Adam Parkin pzelnip at telus.net
Wed Aug 30 23:32:46 PDT 2006


David Bronaugh wrote:
> Or... you could simply do this:
> NumData myNumData(1, 10);
> 
> .. and let the rest follow. AFAIK this is valid syntax; it'll allocate 
> myNumData on the stack.

Yes it is valid, and yes it just allocates onto the stack.

> While not the greatest idea for huge data structures, for something 
> small and lightweight like this, it is ideal.

Yup yup.

> Plus you don't have to think about memory management; when it goes out 
> of scope, you're done.

I'm sure you probably already know this, but of course there is a catch 
if you do something like:

NumData & foo()
{
	NumData n(1,10);
	// do some stuff with n
	return n;
}

As n is destroyed after the return so once the caller of foo tries to 
reference the return value of foo the program chokes (well, technically 
the result is undefined, but bad either way).  And of course if you 
change the return type of foo from "NumData &" to just "NumData" then 
you're implicitly invoking the copy constructor of the class which can 
be a significant performance hit depending on the complexity of the class.

Yet another reason to use a decent language (ie one with garbage 
collection). =;-p
-- 
--
Adam Parkin
E-mail: pzelnip at telus.net
----------------------
Children aren't happy without something to ignore,
And that's what parents were created for.
	-- Ogden Nash


More information about the Discuss mailing list