我应该使用 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.

相关文章