shared_ptr 是一个模板类
shared_ptr< T>
shared_ptr< const T>
const shared_ptr<const T>
Basic shared_ptr Use
std::shared_ptr<std::string> sp(new std::string("hello"));
std::cout << *sp << ", "<< sp->size() << std::endl;
输出结果为:hello, 5
Basic shared_ptr Error
std::shared_ptr<std::string> sp = new std::string("hello");
Compiler error (after substitution):
error C2440: 'initializing' : cannot convert from 'std::string *' to 'std::tr1::shared_ptr<std::string>'
Constructor for class 'std::tr1::shared_ptr<std::string>' is declared 'explicit'
注意:显式(explicit)而非隐式(implicit),错在 = 为隐式赋值;显式赋值: std::shared_ptr<std::string> sp(new std::string("hello"));
Using shared_ptr in Conditionals
std::shared_ptr<int> a;
std::shared_ptr<int> b(new int(137));
std::cout << (a ? "a" : "X") << std::endl;
if (b){
std::cout << "b" << std::endl;
}
else{
std::cout << "X" << std::endl;
}
输出为:X
b
Returning shared_ptr By value
std::shared_ptr<int> foo(int n)
{
std::shared_ptr<int> r(new int(n));
*r += 5;
return r;
}
int main()
{
std::shared_ptr<int> p = foo(3);
std::cout << *p << std::endl;
}
输出为:8
Sharing Ownership with Shared_ptr
std::shared_ptr<int> a(new int (1));
std::shared_ptr<int> b = a;// a,b指向同一个对象
*a += 6;
std::cout << *a << ", " << *b << std::endl;//7, 7
a.reset();
std::cout << "a: " << (a ? "owns" : "empty") << std::endl;
std::cout << "b: " << (b ? "owns" : "empty") << std::endl;
std::cout << *b << std::endl;
// 输出
/*7, 7
a: empty
b : owns
7*/
shared_ptr<const T>
std::shared_ptr<int> frob(new int(100));
std::shared_ptr<const int> look = frob;
std::cout << *look << std::endl;
*frob /= 2;
std::cout << *look << std::endl;
// *look /= 2;// Error 不能给常量赋值
输出:100
50