Effective C++ Item 17 Store newed objects in smart pointer in standalone statements
2014-02-28 15:37
507 查看
If you trying to do multiple things in one statement, you should think carefully abnormal behavior especially exceptions. Let's see an example:
What you expected might be
But it may execute in the order of
if priority() yield exception, you are running into resource leak. Because the pointer will be lost before stored into shared_ptr.
So, what's the suggestion?
Just store newed object in smart pointer in standalone statement.
processWidget(std::tr1::shared_ptr<Widget>(new Widget()), priority());
What you expected might be
new Widget; shared_ptr<Widget>(...); priority();
But it may execute in the order of
new Widget; priority(); shared_ptr<Widget>(...);
if priority() yield exception, you are running into resource leak. Because the pointer will be lost before stored into shared_ptr.
So, what's the suggestion?
Just store newed object in smart pointer in standalone statement.
std::tr1::shared_ptr<Widget> pw(new Widget); processWidget(pw, priority());
相关文章推荐
- Item 17: Store newed objects in smart pointers in standalone statements.(Effective C++)
- Effective C++ 17. Store newed objects in smart pointers in standalone statements
- [Effective C++] Rules 17: Store newed objects in smart pointers in standalone statements
- 条款17:以独立语句将newed对象置入智能指针(Store newed objects in smart pointers in standalone statements)
- [翻译] Effective C++, 3rd Edition, Item 17: 在 standalone statements(独立语句)中将 new 出来的 objects(对象)存入 smart pointers(智能指针)
- Effective C++ Item 17 以独立语句将newed对象置入智能指针
- 读书笔记 effective c++ Item 38 通过组合(composition)为 “has-a”或者“is-implemented-in-terms-of”建模
- Effective C++ Item 14 Think carefully about copying behavior in resource-managing classe
- Effective C++ Item 15 Provide access to raw resources in resource-managing classes
- Implementing a simple smart pointer in c++
- Effective C++ Item 2:Prefer constS, enumS, and inlineS to #defineS
- Effective C++ Item 16 Use the same form in corresponding uses of new and delete
- Effective C++ Item 38 通过复合塑模出 has-a 或 is-implemented-in-terms-of
- Implementing a simple smart pointer in C++
- 读书笔记 effective c++ Item 17 使用单独语句将new出来的对象放入智能指针
- Effective C++ Item 10,11 Have assignment operators return a reference to *this Handle assignment to self in operator =
- effective c++ Item 17: 在一个独立的语句中将 new 出来的对象存入智能指针
- Effective C++ Item 38 通过复合塑模出 has-a 或 is-implemented-in-terms-of
- effective C++ Item 2: Prefer consts, enums, and inlines to #defines
- Effective C++——》条款17:以独立语句将newed的对象置入智能指针