Meyers Singleton:静态关键字混淆
Meyers Singleton : static keyword confusion
考虑以下一段代码,它本质上是 Meyer 的单例示例(希望如此)
static const std::string& foo() // Line 1
{
static std::string str("foo");
return str;
}
第1行提到的static关键字没有意义吗?如果是,为什么?
Is static keyword mentioned in the Line 1 meaningless ? If so why ?
不是没有意义,要不要看你的情况。 static
在 C++ 中在不同的上下文中意味着不同的东西,在这种情况下它使该函数仅在当前编译单元上可用。在 C++ 中实现它的现代方法 - 将函数放入匿名命名空间。
考虑以下一段代码,它本质上是 Meyer 的单例示例(希望如此)
static const std::string& foo() // Line 1
{
static std::string str("foo");
return str;
}
第1行提到的static关键字没有意义吗?如果是,为什么?
Is static keyword mentioned in the Line 1 meaningless ? If so why ?
不是没有意义,要不要看你的情况。 static
在 C++ 中在不同的上下文中意味着不同的东西,在这种情况下它使该函数仅在当前编译单元上可用。在 C++ 中实现它的现代方法 - 将函数放入匿名命名空间。