几年没有接触c ++之后,我又回到了书上,并决定再次使用教科书来学习(“ Sutherland,Bruce。学习C ++用于游戏开发(第59页)。Apress。Kindle版。”)。
我有两个快速问题:

1)
在一个示例中,本书使用以下代码行来调用函数:

string playerInput;
GetPlayerInput( playerInput);


函数本身定义为:

void GetPlayerInput(string& playerInput)
{
    cin >> playerInput;
}


问题:“ playerInput”作为“ string&”传递。真的有必要吗?当我们只需要让函数返回一个字符串并像这样进行操作时,为什么将此作为引用传递:

string playerInput;
playerInput = GetPlayerInput();


和:

string GetPlayerInput()
{
    cin >> playerInput;
    return playerInput;
}


这只是一种风格选择,还是我在这里错过了一些东西?

2)获取用户名的类访问器方法定义为:

'void SetName(const std::string& name);'


没有其他解释。这是什么“ const”东西?我做了一些研究,但感到更加困惑。为什么在将字符串作为参数传递时又需要它?

非常感谢您的帮助!

最佳答案

1)原则上,按价值返回涉及副本。尽管如此,几乎所有编译器都即使在调试模式下也可以执行RVO / NRVO。

因此,通常这是API的选择,但是如果在循环中使用它可能会很重要。比较两者,例如:

for (;;) {
    string playerInput = GetPlayerInput();
    if (playerInput.empty()) break;
    // do something with the playerInput
}

string playerInput;
for (;;) {
    GetPlayerInput(playerInput);
    if (playerInput.empty()) break;
    // do something with the playerInput
}


有一个细微的差异,这使得后面的情况更具性能。在第一种情况下,即使使用NRVO,也每次都会重新分配字符串。相反,在第二种情况下,该字符串仅分配/重新分配了几次,最后它具有最长输入的大小。

另外,GetPlayerInput然后可以返回bool,这将使循环看起来更好:

string playerInput;
while (GetPlayerInput(playerInput)) {
    // do something with the playerInput
}


2)传递const ref(与非const ref相对)不仅使不可能错误地修改参数,而且使使用临时变量成为可能,这可能更为重要。举个例子:

setName("Some name");


不适用于非常量引用。

当按值传递时,会再次涉及到一个副本-它可能会被删除(C ++允许,它的缺点是依赖于复制的代码可能无法工作),但不能保证(并且仅在传递临时对象时才有效) )。

建议使用按值传递的唯一情况是,无论如何都要在内部复制参数,例如:

SomeClass operator +(SomeClass a, const SomeClass& b) {
    return a += b;
}


与之相反

SomeClass operator +(const SomeClass& a, const SomeClass& b) {
    SomeClass result = a;
    return result += b;
}

关于c++ - 传递值作为引用值和“const”值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41461978/

10-12 00:02
查看更多