【发布时间】:2017-05-20 02:16:33
【问题描述】:
假设我有以下代码
Something.hpp
#pragma once
class Something {
public:
static Something& get();
private:
Something();
};
Something.cpp
#include "Something.hpp"
#include <iostream>
using namespace std;
Something& Something::get() {
static Something something;
return something;
}
Something::Something() {
cout << "Something()" << endl;
}
main.cpp
#include <iostream>
using namespace std;
struct SomethingElse {
~SomethingElse() {
Something::get();
cout << "~SomethingElse" << endl;
}
};
void func() {
static SomethingElse something_else;
// do something with something_else
}
int main() {
func();
return 0;
}
可以创建多个Something 对象的实例吗?标准是否对序列化静态对象的销毁有任何规定?
注意我知道跨不同翻译单元时文件级静态变量的破坏是未定义的,我想知道在函数作用域静态变量的情况下会发生什么 (which have the double-checked locking pattern built into the C++ runtime)具有文件级静态变量的相同翻译单元案例,编译器很容易根据变量在代码中的布局方式(静态)确保通过构造和销毁进行序列化,但是当变量是动态延迟创建时会发生什么函数被调用了吗?
注意原始变量呢?我们可以期望它们在程序结束之前包含它们的值吗?因为它们不需要被销毁。
编辑
在 cppreference.com (http://en.cppreference.com/w/cpp/utility/program/exit) 上找到这个
如果线程本地或静态对象 A 的构造函数或动态初始化的完成顺序在线程本地或静态对象 B 之前,则 B 的销毁完成顺序在 A 的销毁开始之前
如果这是真的,那么每个静态对象的销毁都会被序列化?但我也发现了这个
https://isocpp.org/wiki/faq/ctors#construct-on-first-use-v2 与标准相矛盾
【问题讨论】:
-
两个字:共享指针
-
我在标准中找不到关于这种特殊情况的任何信息 - 在终止期间初始化静态对象。我会保证它的安全并假设它是未定义的。
-
@molbdnilo 也许这个问题应该在别处发布?我只是不知道该去哪里
标签: c++ c++11 static-variables