重新分配 boost::shared_array

发布于 2024-10-06 11:02:20 字数 352 浏览 0 评论 0 原文

我有一个共享数组: boost::shared_array myarr(new char[m_length]);

我想重新分配数组。我想创建一个具有所需大小的新共享数组并使用交换增强方法,但这也会复制引用计数。 你还有别的想法吗?

//new_length>m_length
void func(boost::shared_array<char> &myarr,int new_length)
{
       boost::shared_array<char> new_arr(new char[new_length]);
       myarr.swap(new_arr);
}

I have a shared_array:
boost::shared_array myarr(new char[m_length]);

I would like to reallocate the array. I thought of creating a new shared_array with the wanted size and using the swap boost method but this will copy the referance count as well.
Do you have another idea?

//new_length>m_length
void func(boost::shared_array<char> &myarr,int new_length)
{
       boost::shared_array<char> new_arr(new char[new_length]);
       myarr.swap(new_arr);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黑凤梨 2024-10-13 11:02:20

为什么不直接使用 boost::shared_ptr 呢? >?让标准库处理大小调整。

(事实上​​,根据您首先使用shared_array的原因,您很可能只使用std::vector,并小心地通过引用传递它。)

Why not just instead use a boost::shared_ptr<std::vector<char> >? Let the standard library handle resizing.

(In fact, depending on why you were using shared_array in the first place, you might well get away with just using a std::vector, and passing it around by reference carefully.)

很糊涂小朋友 2024-10-13 11:02:20

boost::shared_array::reset 应该可以解决这个问题

myarr.reset(new char[new_length]);

boost::shared_array::reset 删除旧分配的数组,将其与新分配的数组交换。

编辑:忽略这个答案,它不能解决他的问题

boost::shared_array::reset should do the trick

myarr.reset(new char[new_length]);

boost::shared_array::reset deletes the old allocated array, swapping it with the newly allocated one.

Edit: Ignore this answer, it doesn't solve his problem

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文