代码之家  ›  专栏  ›  技术社区  ›  Julian Helfferich

显式选择复制分配

  •  30
  • Julian Helfferich  · 技术社区  · 7 年前

    在C++ 11中,如果复制和移动赋值都可用,则编译器自动选择复制赋值,如果参数是LValk,则如果赋值为rValk,则移动赋值。使用 std::move 可以明确地为左值选择移动分配。但是,如何能够明确地选择右值的复制分配呢?

    代码示例:

    #include <iostream>
    
    class testClass
    {
    public:
        testClass &operator=(const int &other) {
            std::cout << "Copy assignment chosen." << std::endl;
            return *this;
        }
    
        testClass &operator=(int &&other) {
            std::cout << "Move assignment chosen." << std::endl;
            return *this;
        }   
    };  
    
    int main(int argc, char *argv[])
    {
        int a = 4;
        testClass test;
    
        test = a; // Selects copy assignment
        test = 3; // Selects move assignment
    
        test = std::move(a); // Selects move assignment
    //  test = std::copy(3); // <--- This does not work
    
        return 0;
    }
    
    2 回复  |  直到 7 年前
        1
  •  19
  •   user2486888    7 年前

    copy

    template <class T>
    constexpr T& copy(T&& t) noexcept
    {
        return t;
    }
    

    test = copy(a);
    test = copy(3);
    test = copy(std::move(a));
    

    您可以将此函数放在自己的名称空间中,以保持内容的整洁。你也可以为它选择一个更好的名字。


    • 这个 函数接受引用并立即返回相同的引用。它意味着调用方负责控制生存期。
    • =
        2
  •  8
  •   rahnema1    7 年前

    你可以 static_cast const int&

    test = static_cast<const int&>(3);