在堆栈上创建临时对象作为参数 [英] Create temporary object as an argument on the stack

查看:76
本文介绍了在堆栈上创建临时对象作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何没有垃圾收集器指针的编程语言中,我都可以做到

In any programming language without pointers with garbage collector I can do

DrawLine(new Vector(0, 0), new Vector(100, 100));

但是在C ++中,如果DrawLine不负责删除其参数,则无法执行,因此使用两个向量(0,0)(100,100)调用DrawLine的最短方法是:

But in C++ we can't if DrawLine is not responsible for deleting its arguments, so the shortest way to invoke DrawLine with two vectors (0,0) and (100,100) is:

Vector v(0, 0);
Vector w(100, 100);
DrawLine(v, w);

是否有一种方法可以使它成为单个语句?特别是如果vw只是该单个函数的参数,而没有其他函数使用它,则似乎有点冗长.为什么我不能做类似的事情:

Is there a way to make this into a single statement? Especially if v and w are just arguments to that single function and no other function uses it, it seems a bit verbose. Why can't I just do something like:

DrawLine(Vector(0, 0), Vector(100, 100));

推荐答案

为什么我不能做类似的事情:

Why can't I just do something like:

DrawLine(Vector(0, 0), Vector(100, 100));

您正在尝试将临时变量作为参数传递.您可以在3种情况下做到这一点.

You're trying to pass temporary variables as argument. You can do it in 3 cases.

  1. 如果DrawLine采用const引用传递的参数:

  1. If DrawLine takes parameters passed by const reference:

void DrawLine(const Vector& v1, const Vector& v2);

如果可以复制Vector,并且DrawLine采用按值传递的参数:

If Vector could be copied, and DrawLine takes parameters passed by value:

void DrawLine(Vector v1, Vector v2);

如果Vector可以移动,并且DrawLine采用右值引用传递的参数:

If Vector could be moved, and DrawLine takes parameters passed by rvalue reference:

void DrawLine(Vector&& v1, Vector&& v2);

唯一失败的情况是通过非常量引用传递参数,因为临时变量无法绑定到该参数.

The only failing case is passing parameters by non-const reference, since temporary variable couldn't be bound to it.

void DrawLine(Vector& v1, Vector& v2);

这篇关于在堆栈上创建临时对象作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆