我应该使用rvalues写std :: string的构造函数? [英] Should I write constructors using rvalues for std::string?

查看:244
本文介绍了我应该使用rvalues写std :: string的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类:

  class X 
{
std :: string S;
X(const std :: string& s):S(s){}
};

我最近读过一些关于rvalues的信息,我一直在想,如果我应该写构造函数 X 使用rvalue,所以我能够检测 std :: string 类型的临时对象? p>

我认为它应该看起来像:

  X string& s):S(s){} 

至于我的知识,std :: string在支持C ++ 11的编译器中应该使用移动构造函数(如果可用)。

解决方案

  X(std :: string& s) {} 

这不是构造函数采用右值采用右值参考。在这种情况下,您不应该使用 rvalue-references 。而是通过值传递,然后移动到成员:

  X(std :: string s) :S(std :: move(s)){} 

需要复制,在界面中进行。


I have a simple class:

class X
{
    std::string S;
    X (const std::string& s) : S(s) { }
};

I've read a bit about rvalues lately, and I've been wondering, if I should write constructor for X using rvalue, so I would be able do detect temporary objects of std::string type?

I think it should look something like:

X (std::string&& s) : S(s) { }

As to my knowledge, implementation of std::string in compilers supporting C++11 should use it's move constructor when available.

解决方案

X (std::string&& s) : S(s) { }

That is not a constructor taking an rvalue, but a constructor taking an rvalue-reference. You should not take rvalue-references in this case. Rather pass by value and then move into the member:

X (std::string s) : S(std::move(s)) { }

The rule of thumb is that if you need to copy, do it in the interface.

这篇关于我应该使用rvalues写std :: string的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆