Initializing a static pointer in C++
c++, initialization, pointers, static
Solution
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;
Problem
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!