Static Pointer Initialization in C ++

I have a class with a static member that has a pointer like this:

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 this pointer 'm' from another class, for example:

 Animation::m = new QString("testing"); 

He works.

But when I do it like this:

 QString x("Testing"); Animation::m = &x; 

Program crash.

What is wrong with this second method?

I would also like to have this static pointer as private, so I can make the getter and setter static functions for it. The installer should use the second method, since "x" will appear in the parameter, so I'm stuck.

Thanks for any help!

+7
source share
3 answers

I am sure that this is not a failure on this line, and then.

The problem is that you take the address of a variable in automatic memory, and you are probably trying to access it after that. The x variable will be destroyed at the end of the scope, but Animation::m will still point to that memory (a memory that you no longer own after x out of scope). This leads to undefined behavior .

Just as the following would be illegal:

 int* x = NULL; { int k = 3; x = &k; } *x = 4; 

The workaround assigns a value, not a pointer (if previously it was assigned a valid QString* ):

 QString x("Testing"); *(Animation::m) = x; 
+12
source

What is wrong with this second method?

The crash is because you are likely to access it outside the scope in which x was created.

Automatic variables are automatically destroyed after the control leaves the area { } in which they were created. So, outside the scope, you have a pointer pointing to data that does not exist. Access to this data results in Undefined behavior and crashes.

How to do it?

You have to dynamically allocate memory, and then copy the line to the dynamically allocated pointer so that you can access it everywhere. Thus, the string remains valid until explicitly delete ed.

+2
source

I'll bet your program crashes when you use Animation::m after x been destroyed (possibly out of scope).

If you want to use the installer to assign Animation::m , you need to pass the argument as a pointer or by reference:

 class Animation { public: Animation(); void set_m( QString* ptr) { m = ptr; } void set_m( QString& ref) { m = &ref; } private: static QString *m; }; 

However, you still need to make sure that all m indicates that it is still alive when you try to use m .

+1
source

All Articles