C++ 函数内的局部静态变量可以在函数运行之前被初始化吗
展开全部
目前在两个编译器下找到方法,代码不通用。
理论上VS版本的兼容性比较好(然而在clang上编译不过去)。
clang:
#define sendData(something) \
{ \
static char string_[] = (something); \
\
class \
{ \
public: \
static __attribute__((constructor)) void registerString() \
{ \
printf("-------------> Register string: %s\n", string_); \
} \
\
void warningRemover() { }; \
} a; \
a.warningRemover(); \
}
VS(2010):
#define sendData(something) \
{ \
class \
{ \
public: \
static const char *getSomething() \
{ \
return something; \
} \
\
void helperMe() \
{ \
TestClass<getSomething> OMG; \
} \
\
void warningremover() { } \
} helper; \
helper.warningremover(); \
}
template<const char *(*f)()>
class Helper
{
public:
Helper()
{
printf("String -> %s", f());
}
};
template<const char *(*f)()>
class TestClass
{
public:
static Helper<f> g_helper;
TestClass()
{
g_helper;
}
};
template<const char *(*f)()>
Helper<f> TestClass<f>::g_helper;
理论上VS版本的兼容性比较好(然而在clang上编译不过去)。
clang:
#define sendData(something) \
{ \
static char string_[] = (something); \
\
class \
{ \
public: \
static __attribute__((constructor)) void registerString() \
{ \
printf("-------------> Register string: %s\n", string_); \
} \
\
void warningRemover() { }; \
} a; \
a.warningRemover(); \
}
VS(2010):
#define sendData(something) \
{ \
class \
{ \
public: \
static const char *getSomething() \
{ \
return something; \
} \
\
void helperMe() \
{ \
TestClass<getSomething> OMG; \
} \
\
void warningremover() { } \
} helper; \
helper.warningremover(); \
}
template<const char *(*f)()>
class Helper
{
public:
Helper()
{
printf("String -> %s", f());
}
};
template<const char *(*f)()>
class TestClass
{
public:
static Helper<f> g_helper;
TestClass()
{
g_helper;
}
};
template<const char *(*f)()>
Helper<f> TestClass<f>::g_helper;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询