【发布时间】:2011-08-20 06:45:27
【问题描述】:
我发现一些代码使用 std::shared_ptr 在关机时执行任意清理。起初我认为这段代码不可能工作,但后来我尝试了以下方法:
#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;
}
这个程序给出了输出:
At begin of main.
creating std::vector<std::shared_ptr<void>>
Creating test
Test created
Leaving scope
Leaving main
Test destroyed
我对为什么这可能有效有一些想法,这与为 G++ 实现的 std::shared_ptrs 的内部结构有关。由于这些对象将内部指针与计数器包装在一起,因此从std::shared_ptr<test> 到std::shared_ptr<void> 的强制转换可能不会妨碍析构函数的调用。这个假设正确吗?
当然还有更重要的问题:这是否保证符合标准,或者可能进一步更改 std::shared_ptr 的内部结构,其他实现实际上会破坏此代码?
【问题讨论】:
-
您期望会发生什么?
-
那里没有演员 - 这是从 shared_ptr
到 shared_ptr 的转换。 -
仅供参考:这是 MSDN 中有关 std::shared_ptr 的文章的链接:msdn.microsoft.com/en-us/library/bb982026.aspx,这是来自 GCC 的文档:gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a00267.html
标签: c++ c++11 shared-ptr