我有 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
对象。
P.S. 我只学习 C++,只是想了解它是如何工作的。
P.P.S. 在 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);
关于c++ - 最佳做法是在方法中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50124869/