c++11 stl 学习之 shared_ptr
shared_ptr
智能指针 shared_ptr 的声明初始化方式
由于指针指针使用explicit参数 必须显示声明初始化
shared_ptr<string> pNico = new string("nico"); // ERROR
shared_ptr<string> pNico{new string("nico")}; // OK
也可以使用make_shared()
shared_ptr<string> pNico = make_shared<string>("nico");
shared_ptr<string> pJutta = make_shared<string>("jutta");
智能指针一旦声明
就不能再次分配 除非使用reset()
shared_ptr<string> pNico4;
pNico4 = new string("nico");
//ERROR: no assignment for ordinary pointers
pNico4.reset(new string("nico")); // OK
shared_ptr的使用方式与实际指针使用类似 基本没什么区别
示例 sharedPtrTest1()
//=======================================
对于shared_ptr中的参数 可以指定 删除器 Deleter
示例 sharedPtrTest2()
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <fstream> //for ofstream
#include <cstdio> //for remove() using namespace std; void sharedPtrTest1()
{
shared_ptr<string> pNico(new string("nico"));
shared_ptr<string> pJutta(new string("jutta")); (*pNico)[0] = 'N';
pJutta->replace(0, 1, "J"); vector<shared_ptr<string>> whoMadeCoffee;
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico); for (auto ptr : whoMadeCoffee) {
cout << *ptr << " ";
}
cout << endl;
// overwrite a name again
*pNico = "Nicolai";
// print all elements again
for (auto ptr : whoMadeCoffee) {
cout << *ptr << " ";
}
cout << endl;
// print some internal data
cout << "use_count: " << whoMadeCoffee[0].use_count() << endl;
} class FileDeleter
{
private:
std::string filename;
public:
FileDeleter(const std::string& fn)
: filename(fn) {
}
void operator () (std::ofstream* fp) {
fp->close(); //close.file
std::remove(filename.c_str()); //delete file
cout << "delete file finish" << endl;
}
}; void sharedPtrTest2()
{
shared_ptr<std::ofstream> fp(new std::ofstream("tmpfile.txt"),
FileDeleter("tmpfile.txt"));
} int _tmain(int argc, _TCHAR* argv[])
{
sharedPtrTest1();
sharedPtrTest2(); return 0;
}
shared_ptr的误用
下面是错误示例
int* p = new int;
shared_ptr<int> sp1(p);
shared_ptr<int> sp2(p);
这将产生错误 对于int指针有两个智能指针的内存管理器对其进行管理
sp1 sp2 都对其关联的资源进行释放
正确的代码如下:
shared_ptr<int> sp1(new int);
shared_ptr<int> sp2(sp1);
还有一种隐蔽的情况 也会发生这种错误:
比如在Person 中增加一个函数setParentsAndTheirKids()
void setParentsAndTheirKids(shared_ptr<Person> m = nullptr,
shared_ptr<Person> f = nullptr)
{
mother = m;
father = f;
if (m != nullptr){
m->kids.push_back(shared_ptr<Person>(this));
}
if (f != nullptr){
f->kids.push_back(shared_ptr<Person>(thid));
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string name("nico");
shared_ptr<Person> mom(new Person(name + "'s mom"));
shared_ptr<Person> dad(new Person(name + "'s dad"));
shared_ptr<Person> kid(new Person(name + "name"));
kid->setParentsAndTheirKids(mom,dad);
return 0;
}
但是如果在自己的类中使用包含this的shared_ptr指针 会增加引用计数
导致无法释放
所以引进enable_shared_from_this类
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std; class Person : public std::enable_shared_from_this<Person> {
public:
string name;
shared_ptr<Person> mother;
shared_ptr<Person> father;
//vector<shared_ptr<Person>> kids;
vector<weak_ptr<Person>> kids; Person(const string& n,
shared_ptr<Person> m = nullptr,
shared_ptr<Person> f = nullptr)
:name(n), mother(m), father(f){
}; ~Person(){
cout << "delete " << name << endl;
} //====================================
void setParentsAndTheirKids(shared_ptr<Person> m = nullptr,
shared_ptr<Person> f = nullptr)
{
mother = m;
father = f;
if (m != nullptr){
m->kids.push_back(shared_ptr<Person>(shared_from_this()));
}
if (f != nullptr){
f->kids.push_back(shared_ptr<Person>(shared_from_this()));
}
}
}; int _tmain(int argc, _TCHAR* argv[])
{
string name("nico");
shared_ptr<Person> mom(new Person(name + "'s mom"));
shared_ptr<Person> dad(new Person(name + "'s dad"));
shared_ptr<Person> kid(new Person(name + "name")); kid->setParentsAndTheirKids(mom,dad); return 0;
}
c++11 stl 学习之 shared_ptr的更多相关文章
- c++11 stl 学习之 pair
pair以模板的方式存储两个数据 namespace std {template <typename T1, typename T2>struct pair {// memberT1 fi ...
- 侯捷STL学习(11)--算仿+仿函数+适配器
layout: post title: 侯捷STL学习(十一) date: 2017-07-24 tag: 侯捷STL --- 第三讲 标准库内核分析-算法 标准库算法形式 iterator分类 不同 ...
- ###STL学习--关联容器
点击查看Evernote原文. #@author: gr #@date: 2014-08-23 #@email: forgerui@gmail.com STL中的关联容器. ###stl学习 |--迭 ...
- STL学习:STL库vector、string、set、map用法
本文仅介绍了如何使用它们常用的方法. vector 1.可随机访问,可在尾部插入元素:2.内存自动管理:3.头文件#include <vector> 1.创建vector对象 一维: (1 ...
- Effective STL 学习笔记 32 ~ 33
Effective STL 学习笔记 32 ~ 33 */--> div.org-src-container { font-size: 85%; font-family: monospace; ...
- Effective STL 学习笔记: Item 22 ~ 24
Effective STL 学习笔记: Item 22 ~ 24 */--> div.org-src-container { font-size: 85%; font-family: monos ...
- map--C++ STL 学习
map–C++ STL 学习 Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力. 说下map内 ...
- 标准模板库(STL)学习探究之stack
标准模板库(STL)学习探究之stack queue priority_queue list map/multimap dequeue string
- 标准模板库(STL)学习探究之vector容器
标准模板库(STL)学习探究之vector容器 C++ Vectors vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种数据结构和算法的模板类和函数库.vector之所以被 ...
随机推荐
- Spring-data-redis redis
什么是spring-data-redis spring-data-redis是spring-data模块的一部分,专门用来支持在spring管理项目对redis的操作,使用java操作redis最常用 ...
- 搭建php渗透测试环境
php服务器下载地址 http://vdisk.weibo.com/s/D9I4jIIfNddvh 在C盘下创建一个www文件夹 安装phpstudy 下一步安装 修改配置文件 将端口改成8080 保 ...
- 使用WebStorm自动提示nodejs的有关代码
- Could not open Selected VM debug port (8700) (转)
版权声明:本文为博主原创文章,未经博主允许不得转载. 在运行项目的时候,eclipse弹出提示框“Could not open Selected VM debug port (8700). Make ...
- php递归获取目录下所有文件
<?php function getFileList($dir){ $dir=iconv("utf-8","gb2312",$dir); if ($hea ...
- spring boot 启动错误:Could not resolve placeholder
在启动整个spring boot项目时,出现错误: Could not resolve placeholder 原因:没有指定好配置文件,因为src/main/resources下有多个配置文件,例如 ...
- c++ 读入优化、输出优化模板
0. 在有些输入数据很多的变态题中,scanf会大大拖慢程序的时间,cin就更慢了,所以就出现了读入优化.其原理就是一个一个字符的读入,输出优化同理,主要使用getchar,putchar函数. 1. ...
- 创建React组件
组件概述 组件可以将UI切分成一些独立的.可复用的部件,这样你就只需专注于构建每一个单独的部件. 组件从概念上看就像是函数,它可以接收任意的输入值(称之为“props”),并返回一个需要在页面上展示的 ...
- 项目总结11:Centos部署JDK+Tomcat+MySQL文档(阿里云-网易云-华为云)
(如果不是root登陆,则输入:sudo su - 切换成root) 1.JDK安装 1-1-yum update (升级所有包同时也升级软件和系统内核) --安装中会有提示输入y就好(两个y,中 ...
- 【linux C】C语言中常用的几个函数的总结【二】
3.fgets 虽然用 gets() 时有空格也可以直接输入,但是 gets() 有一个非常大的缺陷,即它不检查预留存储区是否能够容纳实际输入的数据,换句话说,如果输入的字符数目大于数组的长度,get ...