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

标签 c++ c++11

我有 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 对象

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/

相关文章:

c++ - 如何获得一个const限定的declval?

c++ - 按名称快速查找用户

c++ - FreeType 链接问题

c++ - 为什么常量的模板特化需要 const 变量

c++ - 我可以安全地混合使用 -std=c++11 和 -std=c++14 编译的库吗?

c++ - 如何将模板类限制为某些内置类型?

c++ - Windows 上的 gmp 库 - 链接错误 LNK2001 未解析的外部符号运算符 <<

c++ - 基类重载方法的访问声明

c++ - 使用容器和字符串时如何强制使用显式分配器类型参数

c++ - 枚举声明点