#include <iostream>
#include <memory>
#include <string>
/*shared_ptr类 智能指针也是模板
*/
void f(std::shared_ptr<std::string> p)
{
std::string* plocal = p.get();//智能指针的get()函数,
std::cout << *plocal << std::endl;//打印普通指针 所指的内容
return;
}
int main(int argc, char const *argv[])
{
std::shared_ptr<std::string> p1(new std::string ("hello world"));//显式
f(p1);
std::shared_ptr<int> p2 = std::make_shared<int>(52);//最安全的分配和使用
std::shared_ptr<std::string> p3 = std::make_shared<std::string>(10,'a');
std::cout << "p2: " << *p2 << "p3 : " << *p3 << std::endl;
auto a = std::make_shared<int>(42);
std::cout << *a << std::endl;
return 0;
}
编译时,记得加上 -std=c++11选项!
-----------------
知识无价!