您的位置:首页 > 其它

shared_ptr智能指针

2017-05-12 22:36 344 查看
#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选项!

-----------------

知识无价!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: