最佳做法是在方法中传递参数
The best practice is to pass an argument in the method
我有map
类:
class map final
{
public:
explicit map(const size_t capacity = 4);
map(const map ©) = 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
的(临时(右值。"不打电话"是什么意思?
相关文章:
- 使用在用于SFINAE的void_t中具有参数的方法
- 如何制作一个将函数作为参数的类方法
- c++方法参数只能在linux的发布模式下自行更改
- 使用用户定义的参数调用future/async并调用类方法
- 将成员函数指针作为参数传递给模板方法
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 具有字符串化的可变参数宏的现代/通用方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何在方法中传递结构参数
- 如何将类成员方法的参数列表自动填充写入可变参数?
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- C++接口继承不同的参数方法
- C++ 模板:重载时找不到基类类型参数方法
- 如何使用迭代器作为参数方法?
- 具有不同亚型的参数方法
- 如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法
- 如何将 C 中声明的可选参数方法转换为 c++
- 如果模板化"ResourceCache"需要不同的创建参数/方法,它们如何加载/创建 T 类型的资源?