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,以便它检测到第一种情况(还有一些实际上我以前没有想过).但是,如果转发器的实现不是内联的,那么第二个可能很难评估.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...