C++核心準(zhǔn)則C.151:使用make_shared構(gòu)建shared_ptr管理的對(duì)象

C.151: Use?make_shared()?to construct objects owned by shared_ptrs
C.151:使用make_shared構(gòu)建shared_ptr管理的對(duì)象
Reason(原因)
make_shared?gives a more concise statement of the construction. It also gives an opportunity to eliminate a separate allocation for the reference counts, by placing the?shared_ptr's use counts next to its object.
make_shared為構(gòu)造動(dòng)作提供了更加簡(jiǎn)明的表達(dá)。由于它將shared_ptr的計(jì)數(shù)置于對(duì)象之后,使用它還可以提供減少另外一次的增加計(jì)數(shù)的機(jī)會(huì)。
Example(示例)
void test() {
// OK: but repetitive; and separate allocations for the Bar and shared_ptr's use count
shared_ptr p {new Bar{7}};
auto q = make_shared(7); // Better: no repetition of Bar; one object
}
Enforcement(實(shí)施建議)
Flag the repetitive usage of template specialization list
提示重復(fù)使用模板特化參數(shù)列表的情況
Flag variables declared to be?shared_ptr
提示使用shared_ptr直接定義變量的情況。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c151-use-make_shared-to-construct-objects-owned-by-shared_ptrs
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評(píng)論
圖片
表情
