【发布时间】:2015-07-17 02:25:56
【问题描述】:
在下面的示例中,在从第一个映射中获取值并插入到第二个映射中之后,共享 ptr 变为空。甚至没有调用析构函数。我不明白到底出了什么问题
#include <iostream>
#include <memory>
#include <unordered_map>
class Test
{
public:
Test(){}
~Test(){}
int test;
};
typedef std::shared_ptr<Test> Test_ptr;
typedef std::unordered_map<std::string, Test_ptr> TestMap;
int main()
{
TestMap map1, map2;
std::string key("abc");
Test_ptr ptr(new Test);
map1.insert(TestMap::value_type(key, ptr));
TestMap::iterator iter = map1.find(key);
if (iter != map1.end())
{
map2.insert(*iter);
if (iter->second == nullptr)
{
std::cout << "after insert the shared ptr becomes null" << std::endl;
}
}
}
g++ -std=c++11 testsharedptr.cpp -o testsharedptr
gcc 版本 4.8.1 (GCC)
【问题讨论】:
-
当我编译并运行这个程序时,它没有打印任何东西。
-
3 for 3 不可重现。你能提供你用来构建的编译器和命令行吗?也许您的特定构建环境中有一些东西?
-
g++ -std=c++11 testsharedptr.cpp -o testsharedptr
-
gcc 版本 4.8.1 (GCC)
标签: c++ shared-ptr