gsyoon wrote:
hi, all.
I'm trying to make a "framework" to store the return value of a
function to a global memory.
My first attempt was
1)
void store_to_global( char * type_name ) {
if ( strcmp( type_name, "CLASS_A") )
previously_allocated_mem = func() ;
...
}
However, there are some classes that override their
assignment operator and making it non-public.
(using copy constructors don't help much as they can
be overridden and made private).
So, I tried to memcpy as
2)
void store_to_global( char * type_name ) {
if ( strcmp( type_name, "CLASS_A") )
memcpy ( previously_allocated_mem, (void*) (&(func())), sizeof
(CLASS_A) ) ;
...
}
memcpying classes is a huge no-no. you're making a copy without going
through "the proper channels" (invoking the copy constructor) and so
you're bypassing the constructor code that will perform a *proper*
copy. And so, the destructors will end up trying to free the same
memory, or fun stuff like that.
2) worked fine for gcc. However, for Solaris CC,
it caused a compile error like
"Error: The "&" operator can only be applied to a variable or other
l-value."
How can I make a general framework to store the return value of
function
regardless of their operators being overridden and made non-public
and the compilers used?
Any comments are welcomed.
Thanks in advance.
Gwang Sik Yoon.
personally, I don't see how such a general framework would be useful,
and why you'd need it to work on types that don't have an accessible
operator= (you can impose at least a couple minimal requirements, can't
you?). And to top it off, you stuff it into a global variable.
anyway, if the function is returning by value, then it would be a
requirement that the type has a copy constructor.
p = std::auto_ptr<T>(new T(func)); // perhaps or something
if the function returns a reference, then you'd be able to get a
pointer to the object and hold onto that perhaps? of course, hard to
say when the pointed-to object would get destroyed and your pointer
would become invalid.
So now you have two different scenarios you'd have to code for. perhaps
use template specialization to execute one set of code if the function
returns a value, and the other if the function returns a reference?