Is there any reasonable use of a function returning an anonymous struct?
Posted
by Akanksh
on Stack Overflow
See other posts from Stack Overflow
or by Akanksh
Published on 2010-04-08T07:18:06Z
Indexed on
2010/04/08
7:23 UTC
Read the original article
Hit count: 369
Here is an (artificial) example of using a function that returns an anonymous struct and does "something" useful:
#include <iostream>
template<typename T>
T* func( T* t, float a, float b )
{
if(!t)
{
t = new T;
t->a = a;
t->b = b;
}
else
{
t->a += a;
t->b += b;
}
return t;
}
struct
{
float a, b;
}* foo(float a, float b)
{
if(a==0) return 0;
return func(foo(a-1,b), a, b);
}
int main()
{
std::cout << foo(5,6)->a << std::endl;
std::cout << foo(5,6)->b << std::endl;
void* v = (void*)(foo(5,6));
float* f = (float*)(v); //[1] delete f now because I know struct is floats only.
std::cout << f[0] << std::endl;
std::cout << f[1] << std::endl;
delete[] f;
return 0;
}
There are a few points I would like to discuss:
- As is apparent, this code leaks, is there anyway I can NOT leak without knowing what the underlying struct definition is? see Comment [1].
- I have to return a pointer to an anonymous struct so I can create an instance of the object within the templatized function
func
, can I do something similar without returning a pointer? - I guess the most important, is there ANY (real-world) use for this at all? As the example given above leaks and is admittedly contrived.
By the way, what the function foo(a,b)
does is, to return a struct containing two numbers, the sum of all numbers from 1 to a and the product of a and b.
EDIT: Maybe the line new T
could use a boost::shared_ptr somehow to avoid leaks, but I haven't tried that. Would that work?
© Stack Overflow or respective owner