Create temporary object as an argument on the stack [closed]

让人想犯罪 __ 提交于 2019-12-11 12:53:38

问题


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.

  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);


来源:https://stackoverflow.com/questions/36955576/create-temporary-object-as-an-argument-on-the-stack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!