5种智能指针指向数组的方法

in 网站建设
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

本文首发于个人博客https://kezunlin.me/post/b82753fc/,欢迎阅读最新内容!

5 methods for c++ shared_ptr point to an array
<!--more-->

Guide

shared_ptr

Prior to C++17, shared_ptr could not be used to manage dynamically allocated arrays. By default, shared_ptr will call delete on the managed object when no more references remain to it. However, when you allocate using new[] you need to call delete[], and not delete, to free the resource.

In order to correctly use shared_ptr with an array, you must supply a custom deleter.

code example

//OK, pointer to int 999
std::shared_ptr<int> sp(new int(999)); 


template< typename T >
struct array_deleter
{
  void operator ()( T const * p)
  { 
    delete[] p; 
  }
};

// pointer to int array, 
// (1) provide array deleter
std::shared_ptr<int> sp(new int[10], array_deleter<int>()); 

// (2) or lambda expression 
std::shared_ptr<int> sp(new int[10], [](int *p) { delete[] p; });

// (3) or use default_delete
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());

// (4) or we can use unique_ptr
std::unique_ptr<int[]> up(new int[10]); // this will correctly call delete[]

// (5) or we use vector<int>, no need to provide deleter 
typedef std::vector<int> int_array_t;
std::shared_ptr<int_array_t> sp(new int_array_t(10));

std::memcpy(sp.get()->data(), arr, size);
std::unique_ptr<int[]> has built-in support for arrays to properly delete[] .

image buffer

std::shared_ptr<uchar> pImage(new uchar[length], std::default_delete<uchar[]>());
memcpy(pImage.get(), (void*)(data.sync_image().data().c_str()), length);
cv::Mat image = cv::Mat(height, width, CV_8UC3, pImage.get());

Reference

History

Copyright

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看