Data returned from another class is garbage
-
Hi,
I guess this a combination of a C++ and Qt question. More C++, but I'm using Qt as my framework.
I have an external class which has a bunch of methods. In one method it returns a pointer to a structure i.e. myStrcture *results.In another class I'm calling the method from the other class to get results, but after I leave the method the results is garbage.
Example
myStructure * results = SecondClass::someMethod(arguments)
//if I look at results it's garbageSecond class:
mystructure *
SecondClass::someMethod(Arguments)
{
//do stuff here
return &results; //So far here is good (when I leave this method I get garbage)
}I also tried this and doesn't help
SecondClass *test = new SecondClass;
myStructure * results = SecondClass->someMethod(arguments)
But still the same results. Any idea how I can get the correct results back. The SecondClass is not a QObject. Not sure if I need that but this I guess is basic C++ issue.Thanks
-
@leinad said in Data returned from another class is garbage:
return &results;
Where is "results" declared? Is it a local variable inside someMethod or is it class member?
-
@leinad said in Data returned from another class is garbage:
The results is declared in the method of the second class.
No wonder it is garbage then.
SecondClass::someMethod(Arguments) { SomeStruct results; // results only exists as long as someMethod is being executed // as soon as someMethod finishes results is destroyed // so, you return a pointer to destroyed object return &results; //So far here is good (when I leave this method I get garbage) }
You have two possibilities:
- Allocate results on the heap (using new)
- Make results class member