问题
In any programming language without pointers with garbage collector I can do
DrawLine(new Vector(0, 0), new Vector(100, 100));
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);
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));
回答1:
Why can't I just do something like:
DrawLine(Vector(0, 0), Vector(100, 100));
You're trying to pass temporary variables as argument. You can do it in 3 cases.
If
DrawLinetakes parameters passed by const reference:void DrawLine(const Vector& v1, const Vector& v2);If
Vectorcould be copied, andDrawLinetakes parameters passed by value:void DrawLine(Vector v1, Vector v2);If
Vectorcould be moved, andDrawLinetakes 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);
来源:https://stackoverflow.com/questions/36955576/create-temporary-object-as-an-argument-on-the-stack