<Item 15> Provide access to raw resources in resource-managing classes

1、You need a way to convert an object of the RAII class (in this case, tr1::shared_ptr) into the raw resource it contains (e.g., the underlying Investment*). There are two general ways to do it: explicit conversion and implicit conversion.

tr1::shared_ptr and auto_ptr both offer a get member function to perform an explicit conversion, i.e., to return (a copy of) the raw pointer inside the smart pointer object:

int days = daysHeld(pInv.get());            // fine, passes the raw pointer
// in pInv to daysHeld

Like virtually all smart pointer classes, TR1::shared_ptr and auto_ptr also overload the pointer dereferencing operators (operator-> and operator*), and this allows implicit conversion to the underlying raw pointers:

class Investment {                         // root class for a hierarchy
public: // of investment types
bool isTaxFree() const;
...
};
Investment* createInvestment(); // factory function
std::tr1::shared_ptr<Investment> // have tr1::shared_ptr
pi1(createInvestment()); // manage a resource bool taxable1 = !(pi1->isTaxFree()); // access resource
// via operator->
...
std::auto_ptr<Investment> pi2(createInvestment()); // have auto_ptr
// manage a
// resource bool taxable2 = !((*pi2).isTaxFree()); // access resource
// via operator*
...

2、The Font class could offer an explicit conversion function such as get:

class Font {
public:
...
FontHandle get() const { return f; } // explicit conversion function
...
};

Unfortunately, this would require that clients call get every time they want to communicate with the API:

void changeFontSize(FontHandle f, int newSize);     // from the C API
Font f(getFont());
int newFontSize;
... changeFontSize(f.get(), newFontSize); // explicitly convert
// Font to FontHandle

Some programmers might find the need to explicitly request such conversions off-putting enough to avoid using the class. That, in turn, would increase the chances of leaking fonts, the very thing the Font class is designed to prevent.

The alternative is to have Font offer an implicit conversion function to its FontHandle:

class Font {
public:
...
operator FontHandle() const { return f; } // implicit conversion function
...
};

That makes calling into the C API easy and natural:  但是隐式转换可能会偷偷造成不想要的转换

Font f(getFont());
int newFontSize;
... changeFontSize(f, newFontSize); // implicitly convert Font
// to FontHandle

3、Often, an explicit conversion function like get is the preferable path, because it minimizes the chances of unintended type conversions. Sometime, however, the naturalness of use arising from implicit type conversions will tip the scales in that direction.但是一切以Item18为原则。Furthermore, some RAII classes combine true encapsulation of implementation with very loose encapsulation of the underlying resource. For example, tr1::shared_ptr encapsulates all its reference-counting machinery, but it still offers easy access to the raw pointer it contains. Like most well-designed classes, it hides what clients don't need to see, but it makes available those things that clients honestly need to access.

4、Things to Remember

  • APIs often require access to raw resources, so each RAII class should offer a way to get at the resource it manages.

  • Access may be via explicit conversion or implicit conversion. In general, explicit conversion is safer, but implicit conversion is more convenient for clients.

<Item 16>Use the same form in corresponding uses of new and delete.

5、When you employ a new expression (i.e., dynamic creation of an object via a use of new), two things happen. First, memory is allocated (via a function named operator new—see Items 49 and 51). Second, one or more constructors are called for that memory. When you employ a delete expression (i.e., use delete), two other things happen: one or more destructors are called for the memory, then the memory is deallocated (via a function named operator delete—see Item 51).

6、 In particular, the memory for an array usually includes the size of the array, thus making it easy for delete to know how many destructors to call. The memory for a single object lacks this information. This is just an example, of course. Compilers aren't required to implement things this way, though many do.

7、This is a particularly important rule to bear in mind when you are writing a class containing a pointer to dynamically allocated memory and also offering multiple constructors, because then you must be careful to use the same form of new in all the constructors to initialize the pointer member. If you don't, how will you know what form of delete to use in your destructor?

8、This rule is also noteworthy for the typedef-inclined, because it means that a typedef's author must document which form of delete should be employed when new is used to conjure up objects of the typedef type. For example, consider this typedef:

typedef std::string AddressLines[];   // a person's address has 4 lines,
// each of which is a string

Because AddressLines is an array, this use of new,

std::string *pal = new AddressLines;   // note that "new AddressLines"
// returns a string*, just like
// "new string[4]" would

must be matched with the array form of delete:

delete pal;                           // undefined!
delete [] pal; // fine

delete 和delete []用错了的话,The result is undefined。使用string和vector来避免动态分配数组。

9、Things to Remember

  • If you use [] in a new expression, you must use [] in the corresponding delete expression. If you don't use [] in a new expression, you mustn't use [] in the corresponding delete expression.

<Item 17>Store newed objects in smart pointers in standalone statements.

10、C++的编译器相比java和C#给予更多语句执行顺序的自由度,exception可能打断正常的执行流程,导致资源泄露

int priority();
void processWidget(std::tr1::shared_ptr<Widget> pw, int priority);
processWidget(new Widget, priority()); //不会编译,没有定义好的隐式转换
processWidget(std::tr1::shared_ptr<Widget>(new Widget), priority());
  1. Execute "new Widget".

  2. Call priority.

  3. Call the tr1::shared_ptr constructor.

可以修正如下

std::tr1::shared_ptr<Widget> pw(new Widget);  // store newed object
// in a smart pointer in a
// standalone statement processWidget(pw, priority()); // this call won't leak

11、Things to Remember

  • Store newed objects in smart pointers in standalone statements. Failure to do this can lead to subtle resource leaks when exceptions are thrown.

<Effective C++>读书摘要--Resource Management<二>的更多相关文章

  1. <Effective C++>读书摘要--Resource Management<一>

    1.除了内存资源以外,Other common resources include file descriptors, mutex locks, fonts and brushes in graphi ...

  2. <Effective C++>读书摘要--Implementations<二>

    <Item29> Strive for exception-safe code. 1.如下面的代码 class PrettyMenu { public: ... void changeBa ...

  3. <Effective C++>读书摘要--Designs and Declarations<一>

    <Item 18> Make interfaces easy to use correctly and hard to use incorrectly 1.That being the c ...

  4. <Effective C++>读书摘要--Inheritance and Object-Oriented Design<二>

    <Item 36> Never redefine an inherited non-virtual function 1.如下代码通过不同指针调用同一个对象的同一个函数会产生不同的行为Th ...

  5. <Effective C++>读书摘要--Designs and Declarations<二>

    <Item 20> Prefer pass-by-reference-to-const to pass-by-value 1.By default, C++ passes objects ...

  6. <Effective C++>读书摘要--Ctors、Dtors and Assignment Operators<二>

    <Item 9> Never call virtual functions during construction or destruction 1.you shouldn't call ...

  7. <Effective C++>读书摘要--Templates and Generic Programming<一>

    1.The initial motivation for C++ templates was straightforward: to make it possible to create type-s ...

  8. <Effective C++>读书摘要--Implementations<一>

    1.For the most part, coming up with appropriate definitions for your classes (and class templates) a ...

  9. <Effective C++>读书摘要--Designs and Declarations<三>

    <Item 22> Declare data members private 1.使数据成员private,保持了语法的一致性,client不会为访问一个数据成员是否需要使用括号进行函数调 ...

随机推荐

  1. Python-爬虫小计

    # -*-coding:utf8-*-import requestsfrom bs4 import BeautifulSoupimport timeimport osimport urllibimpo ...

  2. 随机返回经典语句接口API

    api接口:https://www.liutianyou.com/api/?type=js&charset=utf-8 可以单独将上面链接,在浏览器中查看效果 ​ 这是get请求,参数:typ ...

  3. hadoop生态搭建(3节点)-17.sqoop配置_单节点

    # ==================================================================安装 sqoop tar -zxvf ~/sqoop-1.4.7 ...

  4. python学习笔记:第17天 面向对象03 类与类之间的关系

    一.类与类之间的依赖关系 ⼤千世界, 万物之间皆有规则和规律. 我们的类和对象是对⼤千世界中的所有事物进⾏归类. 那事物之间存在着相对应的关系. 类与类之间也同样如此. 在⾯向对象的世界中. 类与类 ...

  5. Go 入门 - 方法和接口

    方法和接口 方法的接受者 Go中没有类,取而代之的是在结构体上定义的方法 为了将方法(函数)绑定在某一类结构体上,我们在定义函数(方法)时引入"接受者"的概念. 方法接受者在它自己 ...

  6. [HDU6315]Naive Operations(线段树+树状数组)

    构造一个序列B[i]=-b[i],建一颗线段树,维护区间max, 每次区间加后再询问该区间最大值,如果为0就在树状数组中对应的值+1(该操作可能进行多次) 答案在树状数组中找 其实只用一颗线段树也是可 ...

  7. 20154327 Exp6 信息搜集与漏洞扫描

    基础问题回答 (1)哪些组织负责DNS,IP的管理. 全球根服务器均由美国政府授权的ICANN统一管理,负责全球的域名根服务器.DNS和IP地址管理. 全球根域名服务器:绝大多数在欧洲和北美(全球13 ...

  8. 20145234黄斐《Java程序设计》第九周学习总结

    教材学习内容总结 JDBC Java语言访问数据库的一种规范,是一套API.JDBC (Java Database Connectivity) API,即Java数据库编程接口,是一组标准的Java语 ...

  9. 北京Uber优步司机奖励政策(4月8日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  10. 北京Uber优步司机奖励政策(9月28日~10月4日)

    用户组:优步北京人民优步A组(适用于9月28日-10月4日) 滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不 ...