我发现一些代码使用std :: shared_ptr在shutdown时执行任意清理.起初我认为这段代码不可行,但后来我尝试了以下内容:
#include <memory>
#include <iostream>
#include <vector>
class test {
public:
test() {
std::cout << "Test created" << std::endl;
}
~test() {
std::cout << "Test destroyed" << std::endl;
}
};
int main() {
std::cout << "At begin of main.\ncreating std::vector<std::shared_ptr<void>>"
<< std::endl;
std::vector<std::shared_ptr<void>> v;
{
std::cout << "Creating test" << std::endl;
v.push_back( std::shared_ptr<test>( new test() ) );
std::cout << "Leaving scope" << std::endl;
}
std::cout << "Leaving main" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序给出了输出:
At begin of main. …Run Code Online (Sandbox Code Playgroud)