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