item21: 优先使用std::make_unique和std::make_shared,而非直接使用new

// 一个基础版本的std::make_unique
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
    return std::unique_ptr<T>(new T(std::forward<Ts>(param)...));
}
// make 避免代码重复且更安全
auto upw1(std::make_unique<Widget>());  // 使用make函数
std::unique_ptr<Widghet> upw2(new Widget); // 不使用make函数
auto spw1(std::make_shared<Widget>());  // 使用make函数
std::shared_ptr<Widget> spw2(new Widget);  // 使用new

// 特殊case
auto upv = std::make_unique<std::vector<int>>(10, 20);
// make 函数会将它们的参数完美转发给对象构造函数,即生成10个20的std::vector
// 可以这样解决
auto initiList = {10, 20};  // 创建std::initializer_list
auto spv = std::make_shared<std::vector<int>>(initiList);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值