1

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));
trincot
  • 263,463
  • 30
  • 215
  • 251
Carucel
  • 317
  • 3
  • 11
  • 2
    "Why can't I just do something like: `DrawLine(Vector(0, 0), Vector(100, 100));`" Because `DrawLine` is foolish enough to require lvalues or the compiler is broken? – MikeCAT Apr 30 '16 at 13:37
  • 1
    The line [do works](https://ideone.com/isPOZG). Another case that *you* can't do that is that it is banned in your coding conventions. – MikeCAT Apr 30 '16 at 13:41
  • @MikeCAT, Thank you! You are right, it does compile! – Carucel Apr 30 '16 at 13:44

1 Answers1

3

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.

  1. If DrawLine takes parameters passed by const reference:

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

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

    void DrawLine(Vector v1, Vector v2);

  3. 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);
songyuanyao
  • 163,662
  • 15
  • 289
  • 382