c – shared_ptr的静态成员函数make_shared

前端之家收集整理的这篇文章主要介绍了c – shared_ptr的静态成员函数make_shared前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用libc我在公共部分找到std :: shared_ptr :: make_shared()静态成员函数.当我已经定义了类型别名std :: shared_ptr的专业化时,这是非常方便的:
  1. using T = int;
  2. using P = std::shared_ptr< T >;
  3. auto p = P::make_shared(123); // <=> std::make_shared< T >(123)
  4. static_assert(std::is_same< decltype(p),P >::value);

我担心标准合规性,因为来自可信源的文章(1,2)没有提到std :: shared_ptr的静态成员函数make_shared.

现在使用的功能是不好的吗?为什么?

解决方法

使用此静态make_shared成员函数时,您将依赖于g /标准库的实现特定扩展.为了从中获得一点收益,我宁愿保持我的代码可移植,并使用std :: make_shared.

对于您提到的情况,即使用现有的复制或移动构造函数构建新对象,我可以提出一种替代方法(未经测试;对于C 11兼容性,您必须添加尾随返回类型):

  1. template <typename T>
  2. auto share_ptr_to_new(T&& v) {
  3. using T2 = typename std::remove_reference<T>::type;
  4. return std::make_shared<T2>(std::forward<T>(v));
  5. }

在上面的例子中,你可以写自动p = share_ptr_to_new(123).

猜你在找的C&C++相关文章