Answer the question
In order to leave comments, you need to log in
How to keep a stack variable alive?
There is this terrible function:
void someFunction(int index, Value &value) {
switch(index) {
case 0: {
SomeTypeOne t = someObject->someMethodOne(); // возвращает SomeTypeOne
value.type = "SomeTypeOne";
// value.ptr = ???
} break;
case 1: {
SomeTypeTwo t = someObject->someMethodTwo(); // возвращает SomeTypeTwo
value.type = "SomeTypeTwo";
// value.ptr = ???
} break;
default: ;
}
}
struct Value {
QString typeName; // строка
void *ptr;
}
value.ptr = reinterpret_cast<void*>(&t);
*reinterpret_cast<SomeTypeOne*>(value.ptr) = t;
Answer the question
In order to leave comments, you need to log in
Only further calls can extend the life of the variable on the stack. This is the essence of the stack. As soon as you exit the function, the memory is freed for the variables of other functions and all pointers to variables inside become invalid.
template<typename T>
callbackFunction(T &t) {...}
void someFunction(int index)
{
switch(index)
{
case 0: callbackFunction ( someObject->someMethodOne() );
break;
...
First, don't put curly braces in cases, learn the basics of C++ first.
Second, what you're asking is done using new. You get the data, make new for it, then save the data there and attach this memory to the structure.
Some terrible memory operations.
The very essence of the stack is the storage of temporary values that will be automatically removed from memory when the subroutine (procedure or function) exits.
There are two solutions:
1) Use recursion, thus filling the stack and not allowing to remove what is required. But, this is a rather illiterate approach. Recursion has its own range of tasks and is a bit not for such things.
2) Do the right thing - allocate memory on the heap (heap) using the new operator, and pass the pointer to the memory area on the heap inside the function.
void someFunction(int index, Value *value) {
if (value!=NULL)
switch(index) {
case 0:
SomeTypeOne t = someObject->someMethodOne(); // возвращает SomeTypeOne
value->type = "SomeTypeOne";
break;
case 1:
SomeTypeTwo t = someObject->someMethodTwo(); // возвращает SomeTypeTwo
value->type = "SomeTypeTwo";
break;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question