C.151: Use make_shared() to construct objects owned by shared_ptrs
C.151:使用make_shared建構shared_ptr管理的對象
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為構造動作提供了更加簡明的表達。由于它将shared_ptr的計數置于對象之後,使用它還可以提供減少另外一次的增加計數的機會。
Example(示例)
void test() {
// OK: but repetitive; and separate allocations for the Bar and shared_ptr's use count
shared_ptr<Bar> p {new Bar{7}};
auto q = make_shared<Bar>(7); // Better: no repetition of Bar; one object
}
Enforcement(實施建議)
- Flag the repetitive usage of template specialization list<Bar>
- 提示重複使用模闆特化參數清單的情況
- Flag variables declared to be shared_ptr<Bar>
- 提示使用shared_ptr直接定義變量的情況。