最佳做法是在方法中传递参数

The best practice is to pass an argument in the method

本文关键字:参数 方法 最佳      更新时间:2023-10-16

我有map类:

class map final
{
public:
explicit map(const size_t capacity = 4);
map(const map &copy) = delete;
~map();
map &operator=(const map&) = delete;
void add(std::string str);
private:
class impl;
std::unique_ptr<impl> m_impl;
};

默认情况下,方法void add(std::string str);调用复制构造函数,就像我得到的那样。所以我可以使用map.add(std::move(str));来调用移动构造函数。我编写了main函数来展示我是如何理解它的:

int main()
{
map m;
std::string str = "test";
m.add(str); // Copy
m.add("test"); // ?
m.add(std::move(str)); // Move
m.add(std::move("test")); // Move
return 0;
}

在评论中,我写了一个我期望的构造函数版本......对吗?m.add("test");中将调用什么构造函数?

我应该如何更改我的方法签名以调用不支持移动的对象的副本构造函数和其他对象的移动构造函数?包括const对象

附言我只学习C++,只是想了解它是如何工作的。
附言add方法中,不调用std::move()

int main()
{
map m;
std::string str = "test";
m.add(str); // Copy
m.add("test"); // Implicit call to std::string(const char*) ctor
m.add(std::move(str)); // Move
m.add(std::move("test")); // You shouldn't do so. You cast a literal to rvalue here.
return 0;
}

要根据对象功能使用复制或移动构造函数,您应该使用完美的转发技术。喜欢这个

template <typename T>
void add(T&& str);

你传递了一个字符数组,经过一些转换后,它变成了string隐式构造函数的参数,所以整个表达式被视为类型std::string的(临时(右值。"不打电话"是什么意思?