【问题标题】:Should all C++ functions be declared taking rvalue from now?是否应该从现在开始声明所有 C++ 函数都采用右值?
【发布时间】:2014-01-14 09:46:00
【问题描述】:

为什么我应该或不应该创建我的所有函数和成员函数以采用rvalue 而忽略采用lvalue 的版本?您总是可以将lvalue 转发到右值,对吗?我什至可以拥有const rvalue,那么为什么这是一个坏主意或一个好主意?

我在代码中的意思如下。 "&&" rvalue 引用允许用户使用临时对象,并且仍然可以通过简单的转发使用lvalue。所以考虑到这一点,我为什么要提供 c++11 中任何函数的print_string(string& str)(lvalue 参考)(除了const 参考,因为rvalue 很好)?

#include <iostream>
#include <string>
#include <utility>

using namespace std;


void print_string(string&& str)
{
    str += "!!!";
    cout << str << endl;
}
void print_string2(string& str)
{
    str += "???";
    cout << str << endl;
}

int main(int argc, char* argv[])
{

    print_string("hi there");  // works
    print_string(string("hi again")); // works
    string lvalue("lvalue");
    print_string(forward<string>(lvalue)); // works as expected
    //print_string(lvalue);  // compile error

    //print_string2("hi there"); // comile error
    //print_string2(string("hi again")); // compile error
    print_string2(lvalue);


    char a;
    cin >> a;
}

输出

你好!!!
你好,我们又见面了!!!
左值!!!
左值!!!???

void print_string(string&amp;&amp; str) 提供了比void print_string2(string&amp; str) 更灵活的用例,那么为什么我们不应该一直使用右值参数呢?

【问题讨论】:

  • 不!在有意义的地方取一个右值(应用std::move 或提供合理的std::swap 实现),否则坚持const &amp; 或像往常一样传递参数的值。您可能会注意到,考虑到新的 c++11 功能,三规则可能会变成五规则。
  • 按照严格的规则做某事,没有足够的思考,充其量是危险的。为正确的工作使用正确的工具。通过使用 r-value 引用,很明显管理的资源是可移动的,而使用 const l-value ref 则不然。
  • 刚性规则:不要停止思考。
  • 这会使std::foward/std::move 在无数呼叫站点中的使用爆炸式增长,这很愚蠢。
  • 我仍然不明白为什么在所有新功能中,r 值引用是一个避雷针。它充其量只是一个次要功能,旨在解决两个特定问题。 C++11 99% 的新特性更易于了解和使用。

标签: c++ c++11


【解决方案1】:

与 C++ 的许多特性一样,关于如何使用左值和右值引用有一个约定。

另一个约定的例子是运算符,尤其是== 和!=。您可以重载它们以返回doubles,并复制文件以进行比较。但是按照惯例,它们返回 bool 并且只比较左右操作数而不进行修改。


右值引用的约定是它们引用的对象的资源可以被“窃取”:

  • 左值引用意味着对象归其他人所有
  • 右值引用意味着我们可以从对象中窃取资源

已引入右值引用以支持移动语义,即资源所有权的转移。移动语义通常意味着可以移动绑定到右值引用的对象。移出对象通常被假定为处于有效但未知的状态。例如:

// returns a string that equals i appended to p
string join(string&& p, int i); // string&& means: I do something to p. Or not.

// append i to p
void append(string& p, int i);


string my_string = "hello, world."; // length is 13

append(my_string, 42); // I know what state my_string is specified to be in now
my_string[12] = "!"; // guaranteed to work

string result = join( std::move(my_string), 42 );
// what state is my_string now in?
char c = my_string[1]; // is this still guaranteed to work?


string const cresult = join("hello, number ", 5);
// fine, I don't care what state the temporary is in -- it's already destroyed

人们可以想到这样的定义:

string join(string&& p, int i)
{  return std::move(p) + std::to_string(i);  }

void append(string& p, int i)
{  p += std::to_string(i);  }

join 的这个定义确实确实从p 窃取了资源,并且标准确实没有指定p 在操作std::move(p) + std::to_int(i) 之后的状态(这会创建一个临时从p 窃取资源)。

对于这个简单的例子,你仍然可以使用

string result = "hello ";
result = join(std::move(result), 42);

“替换”append。但是移动也可能很昂贵(它们总是会复制一些东西),并且多个左值引用参数不能轻易地被这种技术替换。

注意在我看来,你应该在函数的名称中指出它需要一个左值引用并修改参数。我当然不希望一个名为print_string2 的函数修改我传入的字符串。


恕我直言,移出对象处于有效但未指定状态的约定应该阻止您在任何地方使用右值引用。

此外,当使用太多移动而不是就地操作时,可能会对性能产生轻微影响 à la join。

【讨论】:

    【解决方案2】:

    各种 stackexchange 问题帮助我回答了自己的问题。

    我有前进和移动的困惑。这个答案有帮助 (Can I typically/always use std::forward instead of std::move?) 你可以 r/forward/move/g 我的问题还是一样。请务必直接阅读 Scott Meyer 对此问题的回复:http://scottmeyers.blogspot.co.uk/2012/11/on-superfluousness-of-stdmove.html

    所以这是个好主意吗?好吧,这些帖子帮我弄清楚了:Is pass-by-value a reasonable default in C++11?

    和

    Should all/most setter functions in C++11 be written as function templates accepting universal references?

    和

    Should I always move on `sink` constructor or setter arguments?

    【讨论】:

    • 没有链接一堆人们必须阅读的东西,你能在答案本身中总结你学到的东西吗?
    【解决方案3】:

    print_string2 是一个糟糕的设计。它修改字符串。例如有人可能会写:

    string s{"hello"};
    print_string2(s);     // print the string
    
    foo(s);      // work on the string - oops, it has junk punctuation on it now.
    

    如果一个函数修改了调用者的字符串,那么它不应该被称为print_something。

    所以你说string&amp;&amp; 比string&amp; 更好,但是这两个选项都不是最佳选择。

    相反,这个函数只能按值接受字符串:

    void print_string2(string s)
    

    然后,如果您使用右值(包括 xvalues)调用它,则参数将移动到 s,如果您使用左值调用它,则会制作一个副本,这是理想的行为。

    如果你的函数不需要修改字符串作为其处理的一部分,那么你应该通过 const 引用传递,它可以绑定到右值和左值:

    void print_string(const string &s) 
    {
    

    在您的示例中,这是最好的选择,因为在打印左值时不需要复制字符串。正文将是:

    cout << str << "???" << endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多