指针静态变量的不便 [英] Inconveniences of pointers to static variables
问题描述
我经常使用便利的函数返回指向静态缓冲区是这样的:
I often use convenience functions that return pointers to static buffers like this:
char* p(int x) {
static char res[512];
snprintf(res, sizeof(res)-1, "number is %d", x));
return res;
}
和使用他们所有的地方作为参数传递给其他功能:
and use them all over the place as arguments to other functions:
...
some_func( somearg, p(6) );
....
不过,这种方便,除了有不是线程安全的一个恼人的缺点(可能还有更多的原因):
However, this "convenience" has an annoying drawback besides not being thread-safe (and probably many more reasons):
some_func( somearg, p(6), p(7) );
显然以上没有做我想做的,因为最后两个参数将指向相同的内存空间。我希望能够得到上面,而不很多麻烦正常工作。
The above obviously doesn't do what I want since the last two arguments will point to the same memory space. I would like to be able get the above to work properly without to many hassles.
所以我的问题是:
是否有某种神奇的办法,我已经错过了完成我想要的东西没有做繁琐的配置和放大器;释放?
的*更新2010-04-20的 * 的
* UPDATE 2010-04-20 *
无耻插头:看我自己的答案<一个href=\"http://stackoverflow.com/questions/2231317/inconveniences-of-pointers-to-static-variables/2677237#2677237\">here
Shameless plug: look at my own answer here
我想这会工作,但它也接壤矫枉过正。意见?
I guess it will work but it's also bordering to overkill. Opinions?
推荐答案
我发现了一个替代方法。事情是这样的:
I found an alternate method. Something like this:
#define INIT(n) \
int xi = 0; \
char *x[n]; \
#define MACRO(s) \
(++xi, xi %= sizeof(x)/sizeof(*x), x[xi] = alloca(strlen(s)+1), strcpy(x[xi], (s)), x[xi])
这是我可以称之为是这样的:
that I can call like this:
INIT(2);
some_func( somearg, MACRO("testing1"), MACRO("testing2"));
所以缓冲区是在栈上,而无需任何释放。而且它甚至线程安全的。
So the buffers are on the stack without needing any freeing. And it's even thread-safe.
这篇关于指针静态变量的不便的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!