【发布时间】:2016-09-30 09:40:21
【问题描述】:
您好,我遇到了 const char* 以一种奇怪的方式相同的问题。 Color::Text() 返回一个静态 char 数组,但它也用于初始化数组的 const char* 指针。
如果我想让 rofl::Default 实际工作而不是它 Color::Text 生成的最新“const char”,我该怎么办?
#include <windows.h>
class Color
{
public:
int R;
int G;
int B;
int A;
Color(int r, int b, int g, int a = 255)
{
R = r;
G = g;
B = b;
A = a;
}
const char* Text()
{
static char Texts[124];
snprintf(Texts, 124, "%i %i %i %i", R, G, B, A);
return Texts;
}
}
class rofl
{
public:
const char* Default;
const char* Value;
rofl(const char* d)
{
Default = d;
Value = d;
}
}
rofl dood("0");
rofl doaaod(Color(0,0,0).Text());
rofl xxxx(Color(0,55,0).Text());
int main()
{
printf("%s %s\n", dood.Default, dood.Value);
printf("%s %s\n", doaaod.Default, doaaod.Value);
printf("%s %s\n", xxxx.Default, xxxx.Value);
return 0;
}
输出是:
0 0
0 55 0 0 0 0
0 55 0 0 55 0
【问题讨论】:
-
在
rofl的构造函数中为Default和Value创建一个缓冲区(例如使用new)指向。然后将数据复制到这些缓冲区。更好的是,使用std::string对象而不是char *,动态分配将为您管理干净。
标签: c++ static undefined-behavior behavior