智能指针(1)-std::unique_ptr
std::unique_ptr
std::unique_ptr
是一种几乎和原始指针一样高效的智能指针,对所管理的指针资源拥有独占权。由C++11标准引入,用于替代C++98中过时的std::auto_ptr
智能指针。相比而言,std::unique_ptr
的优点有:
- 语义更清晰:
std::auto_ptr
进行拷贝的时候实际执行的是移动语义,但C++98中并没有定义出移动语义,所以使用的时候可能会违背直觉。而std::unique_ptr
利用了C++11中新定义的移动语义,只允许移动操作,禁止拷贝操作,从而让语义更加清晰。 - 允许自定义删除器:由于
std::unique_ptr
将删除器作为自己的成员变量,所以传入自定义删除器之前需要在模板参数中指定删除器的类型std::unique_ptr<T, D> up(nullptr, deleter)
。 - 支持STL容器:在C++98中,容器要求元素必须是可以拷贝的,比如«effective STL»中提到的,对容器中的元素进行
std::sort
时,会从区间中选一个元素拷贝为主元素(pivot),然后再对所有元素进行分区操作。但是std::auto_ptr
的拷贝操作执行的却是移动语义,这样就会造成bug。在C++11中,STL容器是支持移动语义的,std::unique_ptr
只提供移动操作删除了拷贝操作,并且移动操作是noexcept
的(这一点很重要,因为STL容器有些操作需要保证强异常安全会要求要么用拷贝操作要么用无异常的移动操作)。只要不涉及到拷贝的容器操作,比如fill
函数,那么std::unique_ptr
作为容器元素是正确的。
std::unique_ptr的大小
默认情况下,std::unique_ptr
的大小和原始指针一样:
#include <iostream>
#include <memory>
int main(int argc, const char* argv[]) {
std::unique_ptr<int> upNum(new int);
// 输出8(64位操作系统)
std::cout << sizeof(upNum) << std::endl;
return 0;
}
当添加删除器的时候,情况就发生了变化,std::unique_ptr
的大小就等于原始指针的大小加上删除器类型的大小:
#include <iostream>
#include <memory>
void deleter(int* pNum) {
std::cout << "function deleter" << std::endl;
delete pNum;
}
int main(int argc, const char* argv[]) {
std::unique_ptr<int, decltype(&deleter)> upNum(new int, deleter);
// 输出8+8=16(函数指针类型的大小也为8)
std::cout << sizeof(upNum) << std::endl;
return 0;
}
这种情况是可以优化的,那就是使用仿函数或者lambda函数作为删除器,当仿函数或lambda函数是无状态(stateless)的时候,那么类类型作为类成员变量的时候,会自动优化掉空类所占用的空间:
#include <iostream>
#include <memory>
int main(int argc, const char* argv[]) {
auto deleter = [](int* pNum) {
std::cout << "lambda deleter" << std::endl;
delete pNum;
};
std::unique_ptr<int, decltype(deleter)> upNum(new int, deleter);
// 输出8
std::cout << sizeof(upNum) << std::endl;
return 0;
}
使用场景1-工厂模式
#include <iostream>
#include <memory>
class Foo {
public:
void greeting() noexcept {
std::cout << "hi! i am foo" << std::endl;
}
};
class Factory {
public:
std::unique_ptr<Foo> createFoo() {
return std::unique_ptr<Foo>(new Foo);
}
};
int main(int argc, const char* argv[]) {
auto foo = Factory().createFoo();
// 输出"hi! i am foo"
foo->greeting();
return 0;
}
使用场景2-实现pImpl模式
PIMPL(Pointer to Implementation)是通过将所有成员变量封装到私有的Impl结构体中,自身只保留一个指向结构体对象的一个私有的指针成员。
pImpl模式的优点有:1.降低模块的耦合度,2.提高编译速度,3.提高接口稳定性。
// Foo.h
#pragma once
#include <memory>
#include <string>
class Foo {
public:
Foo();
// 需要将~Foo的实现放入Foo.cpp中,避免出现delete imcomplete type错误
~Foo();
// 1.定义了~Foo之后不会自动生成移动函数
// 2.移动构造函数中因为会生成处理异常的代码,所以需要析构成员变量,也会造成delete imcomplete type问题,所以将实现放入Foo.cpp
// 3.移动赋值函数中因为会先删除自己指向的Impl对象指针,也会造成delete imcomplete type问题,所以将实现放入Foo.cpp
Foo(Foo&& rhs) noexcept;
Foo& operator=(Foo&& rhs) noexcept;
// 由于unique_ptr不支持复制,所以无法生成默认拷贝函数
Foo(const Foo& rhs);
Foo& operator=(const Foo& rhs);
void setName(std::string name);
const std::string& getName() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> m_upImpl;
};
// Foo.cpp
#include "Foo.h"
#include <string>
struct Foo::Impl {
std::string name;
};
Foo::Foo() : m_upImpl(new Impl) {}
Foo::~Foo() = default;
Foo::Foo(Foo&& rhs) noexcept = default;
Foo& Foo::operator=(Foo&& rhs) noexcept = default;
Foo::Foo(const Foo& rhs) : m_upImpl(new Impl) {
*m_upImpl = *rhs.m_upImpl;
}
Foo& Foo::operator=(const Foo& rhs) {
*m_upImpl = *rhs.m_upImpl;
return *this;
}
void Foo::setName(std::string name) {
m_upImpl->name = name;
}
const std::string& Foo::getName() const noexcept {
return m_upImpl->name;
}
尽量使用std::make_unique
使用std::make_unique
来创建std::unique_ptr
智能指针有以下优点:
减少代码重复:从代码
std::unique_ptr<Foo> upFoo(new Foo);
和auto upFoo = std::make_unique<Foo>();
可以得知使用make_unique只需要写一次Foo就可以,更加符合软件工程中的要求。提高异常安全性:当在函数调用中构造智能指针时,由于执行顺序的不确定性,有可能会造成资源泄露,比如对于代码:
#include <iostream>
#include <memory>
#include <exception> bool priority() {
throw std::exception(); return true;
} void func(std::unique_ptr<int> upNum, bool flag) {
if (flag) {
std::cout << *upNum << std::endl;
}
} int main() {
func(std::unique_ptr<int>(new int), priority()); return 0;
}
这里调用func函数时,会执行三个步骤
new int
std::unique_ptr<int>
构造函数priority
函数
这里唯一可以确定的就是步骤1发生在步骤2之前,但步骤3的次序是不一定的,如果步骤3在步骤1和步骤2中间执行那么就会造成内存泄漏。但是如果使用
make_unique
就不会出现这个问题。
但是std::make_unique
是C++14标准才引入的,所以使用C++11环境的话需要自己实现这个函数:
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
- 素材来自于«effective modern c++»
智能指针(1)-std::unique_ptr的更多相关文章
- C++11智能指针之std::unique_ptr
C++11智能指针之std::unique_ptr uniqut_ptr是一种对资源具有排他性拥有权的智能指针,即一个对象资源只能同时被一个unique_ptr指向. 一.初始化方式 通过new云 ...
- c++——智能指针学习(unique_ptr)
1.为什么会有unique_ptr? 动态内存忘记delete,导致内存泄漏.比如: p = new (); if(...) { return ; } delete p; 因此我们需要一种方式来解决这 ...
- 【校招面试 之 C/C++】第27题 C++ 智能指针(三)之 unique_ptr
auto_ptr<string> p1(new string ("auto") : //#1 auto_ptr<string> p2; //#2 p2 = ...
- C++智能指针: auto_ptr, shared_ptr, unique_ptr, weak_ptr
本文参考C++智能指针简单剖析 内存泄露 我们知道一个对象(变量)的生命周期结束的时候, 会自动释放掉其占用的内存(例如局部变量在包含它的第一个括号结束的时候自动释放掉内存) int main () ...
- C++11 新特性之智能指针(shared_ptr, unique_ptr, weak_ptr)
这是C++11新特性介绍的第五部分,涉及到智能指针的相关内容(shared_ptr, unique_ptr, weak_ptr). shared_ptr shared_ptr 基本用法 shared_ ...
- C++ template的一些高级用法(元编码,可变参数,仿函数,using使用方法,. C++ 智能指针)
1 . 通用函数可变参数模板 对于有些时候,我们无法确切的知道,函数的参数个数时,而又不想过多的使用所谓的函数重载,那么就可以效仿下面的例子: #include<iostream> #i ...
- c++智能指针(unique_ptr 、shared_ptr、weak_ptr、auto_ptr)
一.前序 什么是智能指针? ——是一个类,用来存储指针(指向动态分配对象也就是堆中对象的的指针). c++的内存管理是让很多人头疼的事,当我们写一个new语句时,一般就会立即把delete语句直接也写 ...
- C++11 unique_ptr智能指针详解
在<C++11 shared_ptr智能指针>的基础上,本节继续讲解 C++11 标准提供的另一种智能指针,即 unique_ptr 智能指针. 作为智能指针的一种,unique_ptr ...
- c++智能指针的使用,shared_ptr,unique_ptr,weak_ptr
c++智能指针的使用 官方参考 普通指针的烦恼:内存泄漏,多次释放,提前释放 智能指针 负责自动释放所指向的对象. 三种智能指针 shared_ptr,unique_ptr,weak_ptr: 将sh ...
随机推荐
- maven配置settings.xml【阿里云】
<?xml version="1.0" encoding="utf-8"?> <settings xmlns="http://mav ...
- ansible中定义变量的若干方法
Ansible支持十几种定义变量的方式 根据优先级排序的定义方式: Inventory变量 Host Facts变量 Playbook变量 Playbook提示变量 变量文件 命令行变量 1.Inve ...
- linux下查找文件中的某个关键字
1.方法一:grep '关键字' filename 2.方法二:vim filename进入文件里面,不要进入insert编辑模式,直接在normal模式下输入/关键字进行搜索 按n进行查找下一个
- 猜数字 python 3
随机选取一个1-100的整数 通过5次机会猜整数 会提醒猜大或者猜小 当猜对或者已经猜过5次后结束游戏
- C#开发PACS医学影像处理系统(九):序列控件与拖拽
1.先看结构: 创建WPF用户控件:YourTab 创建WPF用户控件:YourItem 创建选项卡时循环添加item,并设置序列缩略图到控件和异步下载的进度条, 1个病人1个或多个Study检查,1 ...
- [LeetCode]1083. 销售分析 II(Mysql,having+if)
题目 编写一个 SQL 查询,查询购买了 S8 手机却没有购买 iPhone 的买家. 题解 使用having + sum+if,而不是自查询. 代码 # Write your MySQL query ...
- docker部署Broketrmq集群
部署Broketrmq集群 通过docker-compose形式部署 首先创建 broker 配置文件,配置文件如下: brokerClusterName = DefaultCluster #集群名 ...
- ams入门了解
另一篇介绍文 https://www.cnblogs.com/clds/p/4985893.html 转载自https://www.cnblogs.com/onlysun/p/4533798.htm ...
- java8的::
public static void main(String[] args) throws Exception { // 第一种方法引用的类型是构造器引用,语法是Class::new,或者更一般的形式 ...
- Prometheus-Alertmanager告警对接到企业微信
之前写过将Prometheus的监控告警信息通过Alertmanager推送到钉钉群. 最近转移了阵地,需要将Prometheus监控告警信息推送到企业微信群,经过两天的摸索,以及查了网上的一些资料, ...