开始。
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <map>
struct Node
{
int i;
double d;
};
typedef boost::shared_ptr<Node> NodePtr;
std::map<int, NodePtr> globalMap;
NodePtr GetSharedPtr(int idx)
{
auto itr = globalMap.find(idx);
if (globalMap.end() == itr)
return NodePtr();
return itr->second;
}
NodePtr& GetSharedPtrRef(int idx)
{
auto itr = globalMap.find(idx);
if (globalMap.end() == itr)
return NodePtr();//warning C4172: returning address of local variable or temporary
//我引用了这个内存,这个内存是临时变量的,变量析构后,内存里的数据就是未定义的了。
return itr->second;
//现在return的是"itr->second"的引用(地址/指针)。
}
int main()
{
//往map中存一个数据Previous。
globalMap.clear();
NodePtr pre = NodePtr(new Node);
pre->i = 0;
pre->d = 0.7;
globalMap[pre->i] = pre;
//有了一个数据current。
NodePtr cur = NodePtr(new Node);
cur->i = 0;
cur->d = 1.1;
NodePtr p1 = GetSharedPtr(cur->i);
if (p1.operator bool() == true)//如果p1里面存储的指针是有效的。
p1 = cur;
if (globalMap.begin()->second->d == cur->d)
std::cout << "1 modify success." << std::endl;
//
NodePtr& p2 = GetSharedPtr(cur->i);
if (p2) p2 = cur;
if (globalMap.begin()->second->d == cur->d)
std::cout << "2 modify success." << std::endl;
//
NodePtr p3 = GetSharedPtrRef(cur->i);
if (p3) p3 = cur;
if (globalMap.begin()->second->d == cur->d)
std::cout << "3 modify success." << std::endl;
//
//将"itr->second"的引用赋值给引用变量后,修改引用变量,才可以修改"itr->second"存储的值。
NodePtr& p4 = GetSharedPtrRef(cur->i);
if (p4) p4 = cur;
if (globalMap.begin()->second->d == cur->d)
std::cout << "4 modify success." << std::endl;
//
return 0;
}
结束。