原来,我认为“为什么会有引用计数这样的技术”是为了内存自动回收和节省内存,但是读完下面的几节后,内存自动回收是一个原因,但是节省内存并不是真正的原因,真正的原因是有些对象如果被复制在现实中是不合事实的。
C++中存在两种语义:值语义(value sematics)和对象语义(object sematic),对象语义也可以叫做引用语义(reference sematics)。
值语义,指的是对象的拷贝与原对象无关,就像拷贝int一样,C++的常用类型数据等都是值语义。
对象语义,指的是面向对象意义下的对象,是禁止拷贝的。
在设计一个类的时候该类是否可以被拷贝(即具备拷贝构造函数),取决于拷贝后的语义是否成立,比如一个Thread类,拷贝后系统中并不会启动另外一个线程,所以拷贝是禁止的。同样类似于Employee雇员类也是。
这么设计起码有两个好处:
1. 语义合理,有些对象复制是不符合常理的
2. 节省内存
#include
#include
#include
#include
class parent;
class children;
typedef boost::shared_ptr parent_ptr;
typedef boost::shared_ptr children_ptr;
class parent
{
public:
~parent() { std::cout <<"destroying parent\n"; }
public:
children_ptr children;
};
class children
{
public:
~children() { std::cout <<"destroying children\n"; }
public:
parent_ptr parent;
};
void test()
{
parent_ptr father(new parent());
children_ptr son(new children);
father->children = son;
son->parent = father;
}
void main()
{
std::cout<<"begin test...\n";
test();
std::cout<<"end test.\n";
}
namespace boost {
template class weak_ptr {
public:
template
weak_ptr(const shared_ptr& r);
weak_ptr(const weak_ptr& r);
~weak_ptr();
T* get() const;
bool expired() const;
shared_ptr lock() const;
};
}
class children
{
public:
~children() { std::cout <<"destroying children\n"; }
public:
boost::weak_ptr parent;
};
最后值得一提的是,虽然通过弱引用指针可以有效的解除循环引用,但这种方式必须在程序员能预见会出现循环引用的情况下才能使用,也可以是说这个仅仅是一种编译期的解决方案,如果程序在运行过程中出现了循环引用,还是会造成内存泄漏的。因此,不要认为只要使用了智能指针便能杜绝内存泄漏。毕竟,对于C++来说,由于没有垃圾回收机制,内存泄漏对每一个程序员来说都是一个非常头痛的问题。