返回一个新对象以及另一个值
我想返回两个值,其中之一是一个新对象。 我可以使用 std::pair 来做到这一点:
class A {
//...
};
std::pair<A*, int> getA()
{
A* a = new A;
//...
}
为了使代码异常安全,我想做:
std::pair<std::auto_ptr<A>, int> getA()
{
std::auto_ptr<A> a(new A);
//...
}
但这不会编译,因为无法复制 auto_ptr
无需修改正在复制的 auto_ptr
。 好吧,这意味着 auto_ptr
不像其他类型那样很好地组合(以另一种方式)。 在这种情况下返回新对象的好方法是什么?
一种替代方法是返回 shared_ptr
,另一种方法是返回 inout 引用。 但我正在寻找其他替代方案。 我可以做这样的事情:
class AGetter
{
void getAExecute()
{
//...
// set a_ and i_
}
std::auto_ptr<A> getA() const
{
return a_.release();
}
int getInt() const
{
return i_;
}
private:
std::auto_ptr<A> a_;
int i_;
};
有更好的方法吗?
I want to return two values, one of which is a new object. I can do this using std::pair
:
class A {
//...
};
std::pair<A*, int> getA()
{
A* a = new A;
//...
}
To make the code exception-safe, I would like to do:
std::pair<std::auto_ptr<A>, int> getA()
{
std::auto_ptr<A> a(new A);
//...
}
But this won't compile as the auto_ptr
cannot be copied without modifying the auto_ptr
being copied. Ok, this means auto_ptr
does not compose well like other types (in one more way). What is a good way of returning a new object in this case?
One alternative is to return a shared_ptr
and another is an inout reference. But I am looking for some other alternative. I can do something like:
class AGetter
{
void getAExecute()
{
//...
// set a_ and i_
}
std::auto_ptr<A> getA() const
{
return a_.release();
}
int getInt() const
{
return i_;
}
private:
std::auto_ptr<A> a_;
int i_;
};
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有两种主要方法可以处理此问题:
shared_ptr
。正如您所发现的那样,auto_ptr 在这种情况下实际上不起作用,但新标准和 Boost 都包含可以执行您想要的操作的引用计数指针。 请告诉我们您不喜欢
shared_ptr
的哪些方面,也许我们可以建议替代方案。There are two major ways to handle this problem:
shared_ptr
.auto_ptr
doesn't really work in these sorts of cases, as you discovered, but the new standard and Boost both contain reference-counted pointers that do what you want. Let us know what you don't like aboutshared_ptr
, and maybe we can suggest an alternative.在这种情况下,
shared_ptr
是理想的选择,但如果您确实不想使用它们,则可以将auto_ptr
返回到包含对象和 int 的对。A
shared_ptr
would be ideal in that situation, but if you really don't want to use those you could return anauto_ptr
to a pair containing the object and the int instead.只需创建一个新类并返回该类
Just create a new class and return that class
它并不漂亮,但您可以通过指针或引用参数返回另一个值:
It's not pretty, but you could return the other value through a pointer or reference argument:
为什么不通过两个参考参数呢?
Why not through two reference parameters?