Chapter 3 Introduction to Resource Management

This chapter is the highlight of the book !

The so-called resource means that once it is used, it must be returned to the system in the future. If you don't, bad things will happen. The most commonly used resource in C++ programs is dynamically allocated memory (if you allocate memory and never return it, it will cause a memory leak), but memory is only one of many resources you must manage. Other common resources include file descriptors, mutex locks, font and brush database connections in graphical interfaces, and network sockets. No matter what kind of resource, the important thing is that when you no longer use it, you must return it to the system.

Trying to ensure the above in any application situation is difficult, but when you consider exceptions, multiple return paths within functions, and program maintainers changing the software without fully understanding the impact that comes, the situation It becomes obvious: the special means of resource management are not yet sufficient.

This chapter begins with a direct, easy-to-understand and object-based resource management method, based on C++'s constructors, destructors, and copying functions. Experience shows that disciplined adherence to these practices can virtually eliminate resource management problems. Then some of the clauses in this chapter will be devoted to memory management. These later specific clauses make up for the lack of previous general clauses, because the object managing the memory must know how to work appropriately and correctly.

  • Item 13: Managing resources with objects
  • Item 14: Be careful with copying behavior in resource management classes
  • Item 15: Provide access to raw resources in resource management classes
  • Item 16: Use new and delete in the same form when used in pairs
  • Item 17: Put newed objects into smart pointers in separate statements

Guess you like

Origin blog.csdn.net/gaochubusheng/article/details/131742300