在堆栈上创建临时对象作为参数

Create temporary object as an argument on the stack

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

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

但是在 C++ 中我们不能,如果 DrawLine 不负责删除它的参数,所以调用 DrawLine 的最短方法是用两个向量 (0,0)(100,100) 是:

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

有没有办法把它变成一条语句?特别是如果 vw 只是该函数的参数而没有其他函数使用它,这似乎有点冗长。为什么我不能做类似的事情:

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

Why can't I just do something like:

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

您正在尝试将临时变量作为参数传递。分3种情况可以做到。

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

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

  2. 如果Vector可以复制,而DrawLine采用值传参:

    void DrawLine(Vector v1, Vector v2);

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

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

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

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