中初始化静态指针

中初始化静态指针

本文介绍了在C ++中初始化静态指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有静态成员的类,它是一个像这样的指针:

I have a class with a static member that's a pointer like so :

animation.h

animation.h

class Animation
{
public:
    Animation();
    static QString *m;

};

animation.cpp

animation.cpp

#include "animation.h"

QString* Animation::m = 0;

Animation::Animation()
{
}

当我尝试从另一个类中初始化"m"指针时:

When I try to initialize that 'm' pointer from another class like so :

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

有效.

但是当我这样做时:

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

程序崩溃.

第二种方法有什么问题?

What is wrong with this second method ?

我还想将静态指针作为私有指针,以便可以对其进行静态getter和setter函数.设置器应使用第二种方法,因为'x'会出现在参数中,所以我被卡住了.

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.

感谢您的帮助!

推荐答案

我敢打赌它不会在那条线上崩溃,但是之后会崩溃.

I bet it's not crashing on that line, but afterwards.

问题是您要获取位于自动内存中的变量的地址,并且可能随后尝试访问它.变量x在作用域结束时将被销毁,但Animation::m仍将指向该内存(x超出作用域后不再拥有的内存).这会导致未定义的行为.

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;

解决方法分配给值,而不是指针(前提是先前已将其分配给有效的QString*):

Workaround assign to the value, not the pointer (provided it was previously assigned to a valid QString*):

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

这篇关于在C ++中初始化静态指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:27