博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective C++ Item 15 Provide access to raw resources in resource-managing classes
阅读量:5817 次
发布时间:2019-06-18

本文共 1346 字,大约阅读时间需要 4 分钟。

In last two item, I talk about resource-managing using RAII, now comes to the practical part. Often, we encounter a situation where an API accept raw resource instead of RAII object. For example:

// You have a shared pointerstd::tr1::shared_ptr
foo(createFoo());// But the API only accept Foovoid acceptFoo(Foo *foo);

In this situation, you need RAII object return raw resources. And there are commonly two ways to do that

 

1. Explicitly provide method to return raw resource of RAII object. That's how shared_ptr handles this situation. shared_ptr have get() method to return raw resource it contains. In addition, it overload -> and * method. This way is safe and clear, but still some make might think it not natural, and we have a second way to accomplish it.

2. Implicitly convert RAII object to raw resource. 

How to do that? Let's see a example

class Font {public:    ...    operator FontHandle() const {        return f;    }private:    FontHandle f;};

We overload operator () to implicitly convert Font to FontHandle and eliminate the use of get(). But this way have a downside. 

Font f1(getFont());// oops, intent to copy a Font object, but wrongly write FontHandler// yet implicitly convertion hold the candle to the devil FontHandler f2 = f1;

If f1 is destroyed and FontHandler is released then f2 become dangle pointer. 

 

转载地址:http://mumbx.baihongyu.com/

你可能感兴趣的文章
修改上一篇文章的node.js代码,支持默认页及支持中文
查看>>
Php实现版本比较接口
查看>>
删除设备和驱动器中软件图标
查看>>
第四章 TCP粘包/拆包问题的解决之道---4.1---
查看>>
html语言
查看>>
从源码看集合ArrayList
查看>>
spring-boot支持websocket
查看>>
菜鸟笔记(一) - Java常见的乱码问题
查看>>
我理想中的前端工作流
查看>>
记一次Git异常操作:将多个repository合并到同一repository的同一分支
查看>>
CodeIgniter 3.0 新手捣鼓源码(一) base_url()
查看>>
Chrome 广告屏蔽功能不影响浏览器性能
查看>>
vSphere 6将于2月2日全球同步发表
查看>>
Android状态栏实现沉浸式模式
查看>>
让你的APP实现即时聊天功能
查看>>
iOS 绝对路径和相对路径
查看>>
使用Openfiler搭建ISCSI网络存储
查看>>
IntPtr 转 string
查看>>
学生名单
查看>>
(转) 多模态机器翻译
查看>>