微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 创建对新对象的引用

我正在学习C,我遇到了以下难题:

作为C新手,我读过,使用引用而不是指针(如果可能的话)通常是一个好主意,所以我试图早日习惯.因此,我有很多方法有一般的形式

void myMethod(ParamClass const& param);

现在,我想知道什么是最好的方法调用这些方法.当然,每个调用都需要一个不同的对象作为参数传递,据我所知,创建它的唯一方法是新的运算符,所以现在我正在做以下操作:

myObject.myMethod(*new ParamClass(...));

虽然这种方法完全可行,但我想知道是否还没有其他已经建立的“c”方式.

谢谢您的帮助!

解决方法

您应该尝试不要使用新的,开始,因为使用它带来内存管理的麻烦.

对于您的示例,只需执行以下操作:

int main(int,char*[])
{
  SomeObject myObject;

  // two phases
  ParamClass foo(...);
  myObject.myMethod(foo);

  // one phase
  myObject.myMethod(ParamClass(...));

  return 0;
}

我推荐第一种方法(两次),因为第二种方法是微妙的.

编辑:评论不是真的适合于描述我所指的那个问题.

正如@Fred Nurk所说,这个标准说明了关于临时人生命的一些事情:

[class.temporary]

(3) Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression,not with any specific subexpression.

(5) The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference [note: except in a number of cases…]

(5) [such as…] A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

这可能会导致两个微妙的错误,大多数编译器不能捕获:

Type const& bound_bug()
{
  Type const& t = Type(); // binds Type() to t,lifetime extended to that of t
  return t;
} // t is destroyed,we've returned a reference to an object that does not exist

Type const& forwarder(Type const& t) { return t; }

void full_expression_bug()
{
  T const& screwed = forwarder(T()); // T() lifetime ends with `;`
  screwed.method(); // we are using a reference to ????
}

Argyrios根据我的要求修补了Clang,以便它检测到第一种情况(还有一些实际上我以前没有想过).但是,如果转发器的实现不是内联的,那么第二个可能很难评估.

原文地址:https://www.jb51.cc/c/115568.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐