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

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

问题描述

我有一个简单的类:

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

我最近阅读了一些关于右值的文章,我一直在想,是否应该使用右值为 X 编写构造函数,这样我就可以检测 的临时对象std::string 类型?

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) { }

据我所知,在支持 C++11 的编译器中实现 std::string 应该在可用时使用它的移动构造函数.

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) { }

这不是一个带有 rvalue 的构造函数,而是一个带有 rvalue-reference 的构造函数.在这种情况下,您不应该使用 rvalue-references.而是通过值传递然后移动到成员中:

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.

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

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