从命名空间可以看出一个是boost的,另一个是tr1的,当然tr1也是从boost中移植过来的,在Windows中需要安装vs2008+sp1补丁才能支持。
智能指针,它们功能一样,都有引用计数的功能,即智能指针被拷贝后会增加引用计数,这样就不用担心之前的智能指针销毁资源而导致拷贝后的智能指针不能用。
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <memory>
struct Widget;
typedef boost::shared_ptr<Widget> WidgetPtr;
typedef std::tr1::shared_ptr<Widget> WidgetTr1Ptr;
struct Widget
{
Widget()
{
std::cout << "Widget" << std::endl;
}
~Widget()
{
std::cout << "~Widget" << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
{
WidgetPtr p1(new Widget());
WidgetTr1Ptr p2(new Widget());
}
system("pause");
return 0;
}
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <string>
class Widget
{
public:
typedef boost::shared_ptr<Widget> pointer;
public:
~Widget()
{
std::cout << "this is destory: " << i_ << std::endl;
}
static pointer create(int i)
{
return pointer(new Widget(i));
}
void test()
{
std::cout << "this is test: " << i_ << std::endl;
}
private:
explicit Widget(int i)
: i_(i)
{
std::cout << "this is create: " << i_ << std::endl;
}
private:
int i_;
};
int main(void)
{
{
Widget::pointer p = Widget::create(1);
p = Widget::create(2);
p = Widget::create(3);
}
const char sep[] = ";";
std::string name = "proxy";
std::string out = name + sep;
std::cout << out << std::endl;
system("pause");
return 0;
}
// 当p指向另外一个智能指针对象时,之前p所指向的对象会自动析构
//输出结果:
// this is create: 1
// this is create: 2
// this is destory: 1
// this is create: 3
// this is destory: 2
// this is destory: 3