I have a class with a static member that's a pointer like so :
animation.h
class Animation
{
public:
Animation();
static QString *m;
};
animation.cpp
#include "animation.h"
QString* Animation::m = 0;
Animation::Animation()
{
}
When I try to initialize that 'm' pointer from another class like so :
Animation::m = new QString("testing");
It works.
But when I do it this way :
QString x("Testing");
Animation::m = &x;
The program crashes.
What is wrong with this second method ?
Also I would like to have that static pointer as private so I can make static getter and setter functions to it. The setter should use the second method as the 'x' will come in a parameter so I'm stuck.
Thanks for any help!
There are two ways to initialize a pointer variable. You can use reference operator & to get memory location of a variable or you can also directly assign one pointer variable to other pointer variable. Examples to initialize pointer variable
A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication. Extern storage class specifies that the variable is defined elsewhere in a large program.
Static and extern are storage classes in C which defines scope and life-time of a variable. Similar to any variables in C, we can use these keywords with pointers for different use cases.
Address of static pointer is constant throughout the execution of program. But where it points-to can be modified. A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.
I bet it's not crashing on that line, but afterwards.
The problem is that you're taking the address of a variable located in automatic memory, and probably try to access it afterwards. The variable x
will be destroyed when it's scope ends, but Animation::m
will still point to that memory (memory you no longer own after x
went out of scope). This results in undefined behavior.
Just like the following would be illegal:
int* x = NULL;
{
int k = 3;
x = &k;
}
*x = 4;
Workaround assign to the value, not the pointer (provided it was previously assigned to a valid QString*
):
QString x("Testing");
*(Animation::m) = x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With