使用scoped_ptr/数组包装分配的输出参数

发布于 2024-08-27 18:02:49 字数 391 浏览 6 评论 0原文

所以, 我有一些代码如下所示:

byte* ar;
foo(ar) // Allocates a new[] byte array for ar 
...
delete[] ar;

为了使这更安全,我使用了scoped_array:

byte* arRaw;
scoped_array<byte> ar;
foo(arRaw);
ar.reset(arRaw);
...
// No delete[]

问题是,是否有任何现有方法可以仅使用scoped_array 来执行此操作,而不使用临时原始数组?

我可能可以编写一个就地“重置器”类,只是想知道该功能是否存在而我错过了它。

谢谢, 担

So,
I have some code which looks like this:

byte* ar;
foo(ar) // Allocates a new[] byte array for ar 
...
delete[] ar;

To make this safer, I used a scoped_array:

byte* arRaw;
scoped_array<byte> ar;
foo(arRaw);
ar.reset(arRaw);
...
// No delete[]

The question is, Is there any existing way to do this using just the scoped_array, without using a temporary raw array?

I can probably write an in-place "resetter" class, just wondering if the functionality exists and I'm missing it.

Thanks,
Dan

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

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

发布评论

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

评论(1

野生奥特曼 2024-09-03 18:02:49

为什么不能只将对作用域数组的引用传递给 foo 并在 foo 内部调用重置?

或者让 foo 返回 boost::shared_array/ptr 如下

boost::shared_array<byte> foo()
{
  boost::shared_array<byte> a (new byte[100]);
  return a;
}

boost::shared_array<byte> ar = foo();

编辑:

既然你不能更改 foo 那么下面的怎么样?

byte* rawArray;
foo (rawArray);
boost::scoped_array<byte> array (rawArray);

或者,您可以按如下方式重载 foo

boost::shared_array<byte> foo()
{
    byte* rawArray;
    foo (rawArray);
    return boost::shared_arry<byte> (rawArray);
}

,然后按如下方式使用重载版本

boost::shared_array<byte> array = foo();

Why can't you just pass a reference to the scoped array to foo and call reset inside of foo?

Alternatively have foo return a boost::shared_array/ptr as follows

boost::shared_array<byte> foo()
{
  boost::shared_array<byte> a (new byte[100]);
  return a;
}

boost::shared_array<byte> ar = foo();

Edit:

Since you cannot change foo how about the following?

byte* rawArray;
foo (rawArray);
boost::scoped_array<byte> array (rawArray);

Alternatively you can overload foo as follows

boost::shared_array<byte> foo()
{
    byte* rawArray;
    foo (rawArray);
    return boost::shared_arry<byte> (rawArray);
}

and then use the overloaded version as follows

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