c++ - 创建对新对象的引用

标签 c++ parameter-passing reference-type

我刚刚学习 C++,遇到了以下难题:

作为 C++ 新手,我读到过使用引用而不是指针(如果可能)通常是个好主意,所以我想尽早养成这个习惯。因此,我有很多具有一般形式的方法

void myMethod(ParamClass const& param);

现在,我想知道调用这些方法的最佳方式是什么。当然,每次调用都需要将不同的对象作为参数传递,据我所知,创建它的唯一方法是 new 运算符,所以现在我正在执行以下操作:

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

虽然这种方法完全有效,但我想知道是否还有另一种已经建立的“C++ 方式”可以做到这一点。

感谢您的帮助! 丹

最佳答案

一开始你应该尽量不要使用new,因为使用它会带来内存管理的麻烦。

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

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,以便它检测到第一种情况(实际上还有一些我最初没有想到的)。然而,如果 forwarder 的实现不是内联的,则第二个可能很难评估。

关于c++ - 创建对新对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4863324/

相关文章:

c - 了解有关 C 'bomb' 的 x86 语法

c# - 我可以在这里将引用类型视为值类型吗,还是需要克隆?

c# - ValueTypes 如何从 Object (ReferenceType) 派生并仍然是 ValueTypes?

c++ - 如何挑出发送给仅采用可变参数的宏的第一个参数

c++ - 什么是 C++ 中的隐式取消引用

c++ - rapidxml:如何遍历节点?遗漏了最后一个 sibling

c++ - 从位置(到位置)读取文件

unit-testing - 创建一个 `std::env::Args` 迭代器用于测试

javascript - 我正在尝试使用 div 名称作为变量来打开和关闭多个按钮的 div

c# - 引用问题: when are two objects equal?