考虑以下程序.
struct s { ~s(); };
void f()
{
static s a;
}
struct t { ~t() { f(); } };
int main()
{
static s b;
static t c;
}
Run Code Online (Sandbox Code Playgroud)
我试图找出关于静态对象破坏的标准保证是什么,但我发现C++ 03 [basic.start.term]的文本相当不足.
是否定义了程序的行为?如果是这样,静态对象的破坏顺序是什么a,b并且c?如果会发生什么s::~s引发了异常?请解释您的推理,最好使用标准中的引号.
我在下一个代码中遇到了析构函数的一些问题:
#include <stdlib.h>
#include <cstdio>
class Foo2
{
public:
Foo2() { printf("foo2 const\n"); }
~Foo2()
{
printf("foo2 dest\n"); // <--- wasn't called for bionic libc
}
};
static Foo2& GetFoo2()
{
static Foo2 foo2;
printf ("return foo2\n");
return foo2;
}
class Foo1
{
public:
Foo1() { printf("foo1 const\n"); }
~Foo1()
{
printf("foo1 dest\n");
GetFoo2();
}
};
int main( int argc, const char* argv[] )
{
printf("main 1 \n");
static Foo1 anotherFoo;
printf("main 2 \n");
}
Run Code Online (Sandbox Code Playgroud)
为什么不要求foo2的析构函数bionic用于glibc? …
我有以下情况:在标头“test.hpp”中我定义:
class ObjectA {
public:
ObjectA();
~ObjectA();
static ObjectA & get_A();
};
class ObjectB {
public:
~ObjectB();
static ObjectB & get_B();
void do_cleanup();
};
Run Code Online (Sandbox Code Playgroud)
在单独的编译单元中,我实现了 ObjectB:
#include "test.hpp"
#include <iostream>
ObjectB::~ObjectB() {
std::cout<<"ObjectB dtor"<<std::endl;
}
ObjectB & ObjectB::get_B() {
thread_local ObjectB b_instance;
return b_instance;
}
void ObjectB::do_cleanup() {
std::cout<<"Clearing up B garbage..."<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
对象A:
#include "test.hpp"
#include <iostream>
ObjectA::ObjectA() {
ObjectB::get_B(); <--dummy call to initialize thread_local ObjectB;
}
ObjectA::~ObjectA() {
std::cout<<"ObjectA dtor"<<std::endl;
ObjectB::get_B().do_cleanup(); // <-- is this undefined behaviour??
} …Run Code Online (Sandbox Code Playgroud)