Item 17:store newed objects in smart pointers in standalone statements.
Puts the new object into a smart pointer in a separate statement, which is a resource leak caused by other expressions throwing exceptions. Because C + + differs from other languages, the order of calculation of function parameters is largely determined by the compiler.
If you're doing Windows programming, or DLL development, May often encounter similar __cdecl
, __stdcall
and other keywords. They are to specify the parameters in the stack order. A discussion of functions and parameters can be consulted: C + + Manuscripts: Functions and Parameters
or to give an example of clarity:
processwidget ( shared_ptr < widget > ( new widget priority ());
In the preceding code, the processWidget
arguments are evaluated first before the function is called. The process can be considered to consist of three parts:
- Implementation
new Widget
;
- Structure
shared_ptr<Widget>
;
- Called
priority()
.
In most cases the compiler has the right to determine the order of the three parts of the process, and if it is unfortunate for some efficiency reason, the compiler considers the order 1, 3, 2
to be, namely:
- Implementation
new Widget
;
- Called
priority()
.
- Structure
shared_ptr<Widget>
;
So if priority
throws an exception, the new widget
will never find it back." Although we use smart pointers everywhere, the resources are leaking!
So in a more robust implementation, you should separate the statements that create the resource and initialize the smart pointer:
shared_ptr < widget > PW = shared_ptr < widget > ( new Widget processwidget ( PW , priority ());
Unless noted, this blog article is original, reproduced please link to the form of this article address: http://harttle.com/2015/08/08/effective-cpp-17.html
Copyright NOTICE: This article is for bloggers original articles, reproduced please attach the original link.
Item 17: Put the new object into a smart pointer in a separate statement effective C + + notes