移动分配与标准复制和交换不兼容

时间:2013-11-07 16:41:39

标签: c++ c++11 move-semantics copy-and-swap

测试新的Move Semantics。

我刚刚询问了移动构造函数的问题。但是,正如评论中所述,当您使用标准的“复制和交换”习惯时,问题实际上是“移动分配”操作符和“标准分配”操作符发生冲突。

这是我正在使用的课程:

#include <string.h>
#include <utility>

class String
{
    int         len;
    char*       data;

    public:
        // Default constructor
        // In Terms of C-String constructor
        String()
            : String("")
        {}

        // Normal constructor that takes a C-String
        String(char const* cString)
            : len(strlen(cString))
            , data(new char[len+1]()) // Allocate and zero memory
        {
            memcpy(data, cString, len);
        }

        // Standard Rule of three
        String(String const& cpy)
            : len(cpy.len)
            , data(new char[len+1]())
        {
            memcpy(data, cpy.data, len);
        }
        String& operator=(String rhs)
        {
            rhs.swap(*this);
            return *this;
        }
        ~String()
        {
            delete [] data;
        }
        // Standard Swap to facilitate rule of three
        void swap(String& other) throw ()
        {
            std::swap(len,  other.len);
            std::swap(data, other.data);
        }

        // New Stuff
        // Move Operators
        String(String&& rhs) throw()
            : len(0)
            , data(null)
        {
            rhs.swap(*this);
        }
        String& operator=(String&& rhs) throw()
        {
            rhs.swap(*this);
            return *this;
        }
};

我认为是漂亮的沼泽标准。

然后我测试了我的代码:

int main()
{
    String  a("Hi");
    a   = String("Test Move Assignment");
}

此处a的分配应使用“移动分配”运算符。但是与“标准作业”操作符发生冲突(作为标准副本和交换编写)。

> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

> g++ -std=c++11 String.cpp
String.cpp:64:9: error: use of overloaded operator '=' is ambiguous (with operand types 'String' and 'String')
    a   = String("Test Move Assignment");
    ~   ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String.cpp:32:17: note: candidate function
        String& operator=(String rhs)
                ^
String.cpp:54:17: note: candidate function
        String& operator=(String&& rhs)
                ^

现在我可以通过将“标准分配”操作符修改为:

来解决此问题
    String& operator=(String const& rhs)
    {
        String copy(rhs);
        copy.swap(*this);
        return *this;
    }

但这并不好,因为它混淆了编译器优化复制和交换的能力。请参阅什么是复制和交换习惯用法? herehere

我错过了一些不太明显的东西吗?

3 个答案:

答案 0 :(得分:24)

如果定义赋值运算符以获取值,则不应(不需要也不能)定义采用rvalue-reference的赋值运算符。没有意义。

通常,当您需要区分左值和右值时,您只需要提供一个带右值引用的重载,但在这种情况下,您选择的实现意味着您不需要进行区分。无论你是左值还是右值,你都要创建参数并交换内容。

String f();
String a;
a = f();   // with String& operator=(String)

在这种情况下,编译器会将调用解析为a.operator=(f());它将意识到返回值的唯一原因是operator=的参数并且将删除任何副本 - 这是使函数在第一时间取值!

答案 1 :(得分:8)

其他答案建议只有一个重载operator =(String rhs)按值获取参数,但这是最有效的实现。

在这个例子中,DavidRodríguez确实如此 - dribeas

String f();
String a;
a = f();   // with String& operator=(String)

没有复制。但是,假设只提供operator =(String rhs)并考虑此示例:

String a("Hello"), b("World");
a = b;

会发生什么

  1. b已复制到rhs(内存分配+ memcpy);
  2. arhs已交换;
  3. rhs被销毁。
  4. 如果我们实现operator =(const String& rhs)operator =(String&& rhs),那么当目标的长度大于源的长度时,我们可以避免步骤1中的内存分配。例如,这是一个简单的实现(不完美:如果Stringcapacity成员可能会更好:

    String& operator=(const String& rhs) {
        if (len < rhs.len) {
            String tmp(rhs);
            swap(tmp);
        else {
            len = rhs.len;
            memcpy(data, rhs.data, len);
            data[len] = 0;
        }
        return *this;
    }
    
    String& operator =(String&& rhs) {
        swap(rhs);
    }
    

    如果swapnoexcept,那么除了效果点之外,operator =(String&&)也可以是noexcept。 (如果“潜在”执行内存分配,情况并非如此。)

    在Howard Hinnant的这篇优秀explanation中查看更多详情。

答案 2 :(得分:3)

复制和分配所需要的只是:

    // As before
    String(const String& rhs);

    String(String&& rhs)
    :   len(0), data(0)
    {
        rhs.swap(*this);
    }

    String& operator = (String rhs)
    {
        rhs.swap(*this);
        return *this;
    }

   void swap(String& other) noexcept {
       // As before
   }