Class 具有静态链接的类
如果我没记错的话,静态链接意味着一个变量或函数是其编译单元的本地变量或函数。这意味着在其他编译单元中可能存在具有相同名称和参数的变量或函数 我想在课堂上用这个 假设我有多个编译单元,需要确保在退出时正确删除。所以我使用atexit处理程序。但是每个编译单元都应该将自己的atexit处理程序放在适当的位置。Class 具有静态链接的类,class,c++11,static,Class,C++11,Static,如果我没记错的话,静态链接意味着一个变量或函数是其编译单元的本地变量或函数。这意味着在其他编译单元中可能存在具有相同名称和参数的变量或函数 我想在课堂上用这个 假设我有多个编译单元,需要确保在退出时正确删除。所以我使用atexit处理程序。但是每个编译单元都应该将自己的atexit处理程序放在适当的位置。 我做了一个这样的课程: class Init { private: static Init* self; Init() { std::atexit(Init:
我做了一个这样的课程:
class Init {
private:
static Init* self;
Init() {
std::atexit(Init::cleanup);
}
static void cleanup() {
// Do cleanup
}
};
Init* Init::self = new Init;
但是,如果在不同的CU中有多个名为Init
的类,链接器就会感到困惑。而且编译器不允许我执行静态类Init{…}
如何存档清理(如果可能,使用名为
Init
)的类?您可以将类放入未命名的命名空间中
然后,虽然类型没有链接,但也会产生相同的效果
// Everything inside here is unique to this TU
namespace {
class Init { /** whatever **/ };
Init* Init::self = new Init;
}
int main()
{
// "Init" in here will refer to that which you created above
}
您可以将类放入未命名的命名空间中 然后,虽然类型没有链接,但也会产生相同的效果
// Everything inside here is unique to this TU
namespace {
class Init { /** whatever **/ };
Init* Init::self = new Init;
}
int main()
{
// "Init" in here will refer to that which you created above
}
@马丁尼:不急。“甚至有人可能会提出一个更好的主意。”马丁尼:不要着急。甚至,其他人可能会提出一个更好的主意。