我应该使用 std::string 的右值编写构造函数吗?

2023-09-26C/C++开发问题
3

本文介绍了我应该使用 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 的右值编写构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6