C++学习笔记-Move Assignment Operator

移动赋值操作符(Move Assignment Operator)是移动语义的重要组成部分,当我们需要将一个对象赋值给另一个已存在的对象时,移动赋值操作符可以高效地转移资源而不是拷贝资源。

基本移动赋值操作符

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>

class String
{
public:
    String() = default;
    String(const char* str)
    {
        m_Size = strlen(str);
        m_Buffer = new char[m_Size + 1];
        memcpy(m_Buffer, str, m_Size);
        m_Buffer[m_Size] = 0;
    }

    String(const String& other)
    {
        m_Size = other.m_Size;
        m_Buffer = new char[m_Size + 1];
        memcpy(m_Buffer, other.m_Buffer, m_Size);
        m_Buffer[m_Size] = 0;
    }

    String(String&& other) noexcept
    {
        std::cout << "Moved...\n";
        m_Size = other.m_Size;
        m_Buffer = other.m_Buffer;

        other.m_Size = 0;
        other.m_Buffer = nullptr;
    }

    /* 当我们已经有一个String并赋值另一个String时,我们需要移动赋值操作符 */
    String& operator=(String&& other) noexcept
    {
        // 检查是否移动的对象是不是自己,防止自己移动自己
        if (this != &other)
        {
            std::cout << "Moved...\n";
            delete[] m_Buffer; // 因为我们已经有一个String对象了,所以我们需要删除现有的,实际上是替换

            m_Size = other.m_Size;
            m_Buffer = other.m_Buffer;

            other.m_Size = 0;
            other.m_Buffer = nullptr;
        }
        return *this;
    }

    ~String()
    {
        delete[] m_Buffer;
    }

    void Print() 
    { 
        for(int i = 0; i < m_Size; i++)
            std::cout << m_Buffer[i];
        std::cout << "\n";
    }

private:
    char* m_Buffer;
    size_t m_Size;
};

class Entity
{
public:
    Entity(const String& name) : m_Name(name) {}

    Entity(String&& name) : m_Name(std::move(name)) {}

    void PrintName()
    {
        m_Name.Print();
    }
private:
    String m_Name;
};

void BasicMoveAssignmentDemo()
{
    std::cout << "=== Basic Move Assignment Demo ===" << std::endl;
    
    String str1 = "Hello";
    //String str2 = std::move(str1); // 这会调用移动构造函数
    String str2;

    std::cout << "str1: ";
    str1.Print();
    std::cout << "str2: ";
    str2.Print();

    str2 = std::move(str1); // 这会调用移动赋值操作符

    std::cout << "str1: ";
    str1.Print();
    std::cout << "str2: ";
    str2.Print();

    /*
    总结
    1. 当我们已经有一个字符串并为其赋值时,我们使用std::move
    */
}

int main()
{
    BasicMoveAssignmentDemo();
    return 0;
}

详细的移动赋值操作符实现

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#include <iostream>
#include <string>
#include <vector>
#include <memory>

class ResourceManager
{
private:
    int* data;
    size_t size;
    std::string name;
    
public:
    // 构造函数
    ResourceManager(const std::string& n = "unnamed", size_t s = 0) 
        : name(n), size(s), data(nullptr)
    {
        if (size > 0)
        {
            data = new int[size];
            for (size_t i = 0; i < size; ++i)
            {
                data[i] = static_cast<int>(i + 1);
            }
        }
        std::cout << "Constructed: " << name << " (size: " << size << ")" << std::endl;
    }
    
    // 拷贝构造函数
    ResourceManager(const ResourceManager& other)
        : name(other.name + "_copy"), size(other.size), data(nullptr)
    {
        if (size > 0)
        {
            data = new int[size];
            std::copy(other.data, other.data + size, data);
        }
        std::cout << "Copy constructed: " << name << " from " << other.name << std::endl;
    }
    
    // 移动构造函数
    ResourceManager(ResourceManager&& other) noexcept
        : data(other.data), size(other.size), name(std::move(other.name))
    {
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move constructed: " << name << std::endl;
    }
    
    // 拷贝赋值操作符
    ResourceManager& operator=(const ResourceManager& other)
    {
        std::cout << "Copy assignment: " << name << " = " << other.name << std::endl;
        
        if (this != &other)
        {
            // 清理现有资源
            delete[] data;
            
            // 拷贝新资源
            name = other.name + "_assigned";
            size = other.size;
            data = nullptr;
            
            if (size > 0)
            {
                data = new int[size];
                std::copy(other.data, other.data + size, data);
            }
        }
        return *this;
    }
    
    // 移动赋值操作符
    ResourceManager& operator=(ResourceManager&& other) noexcept
    {
        std::cout << "Move assignment: " << name << " = " << other.name << std::endl;
        
        if (this != &other)
        {
            // 清理现有资源
            delete[] data;
            
            // 移动新资源
            data = other.data;
            size = other.size;
            name = std::move(other.name);
            
            // 将源对象置于有效但未指定的状态
            other.data = nullptr;
            other.size = 0;
        }
        return *this;
    }
    
    // 析构函数
    ~ResourceManager()
    {
        if (data)
        {
            std::cout << "Destroyed: " << name << " (had data)" << std::endl;
            delete[] data;
        }
        else
        {
            std::cout << "Destroyed: " << name << " (no data)" << std::endl;
        }
    }
    
    // 工具函数
    void print() const
    {
        std::cout << "ResourceManager '" << name << "': size=" << size;
        if (data && size > 0)
        {
            std::cout << ", data=[" << data[0];
            if (size > 1) std::cout << ", " << data[1];
            if (size > 2) std::cout << ", ...";
            std::cout << "]";
        }
        else
        {
            std::cout << ", no data";
        }
        std::cout << std::endl;
    }
    
    bool hasData() const { return data != nullptr; }
    size_t getSize() const { return size; }
    const std::string& getName() const { return name; }
};

void DetailedMoveAssignmentDemo()
{
    std::cout << "=== Detailed Move Assignment Demo ===" << std::endl;
    
    // 1. 基本移动赋值
    std::cout << "\n1. Basic move assignment:" << std::endl;
    
    ResourceManager rm1("original", 5);
    ResourceManager rm2("target", 3);
    
    rm1.print();
    rm2.print();
    
    rm2 = std::move(rm1); // 移动赋值
    
    std::cout << "After move assignment:" << std::endl;
    rm1.print();
    rm2.print();
    
    // 2. 自赋值测试
    std::cout << "\n2. Self-assignment test:" << std::endl;
    
    ResourceManager rm3("self_test", 4);
    rm3.print();
    
    rm3 = std::move(rm3); // 自移动赋值
    rm3.print();
    
    // 3. 链式赋值
    std::cout << "\n3. Chained assignment:" << std::endl;
    
    ResourceManager rm4("first", 2);
    ResourceManager rm5("second", 3);
    ResourceManager rm6("third", 4);
    
    rm6 = rm5 = std::move(rm4); // 链式赋值
    
    std::cout << "After chained assignment:" << std::endl;
    rm4.print();
    rm5.print();
    rm6.print();
}

// 移动赋值在容器中的应用
void ContainerMoveAssignmentDemo()
{
    std::cout << "\n=== Container Move Assignment Demo ===" << std::endl;
    
    std::vector<ResourceManager> container1;
    std::vector<ResourceManager> container2;
    
    // 填充第一个容器
    container1.emplace_back("item1", 10);
    container1.emplace_back("item2", 20);
    container1.emplace_back("item3", 30);
    
    std::cout << "Container1 contents:" << std::endl;
    for (const auto& item : container1)
    {
        item.print();
    }
    
    // 移动整个容器
    container2 = std::move(container1);
    
    std::cout << "\nAfter moving container1 to container2:" << std::endl;
    std::cout << "Container1 size: " << container1.size() << std::endl;
    std::cout << "Container2 size: " << container2.size() << std::endl;
    
    std::cout << "Container2 contents:" << std::endl;
    for (const auto& item : container2)
    {
        item.print();
    }
    
    // 移动单个元素
    std::cout << "\n3. Moving individual elements:" << std::endl;
    
    ResourceManager standalone("standalone", 15);
    standalone.print();
    
    // 将standalone移动到容器中
    container2.push_back(std::move(standalone));
    
    std::cout << "After moving standalone to container:" << std::endl;
    standalone.print();
    container2.back().print();
}

int main()
{
    DetailedMoveAssignmentDemo();
    ContainerMoveAssignmentDemo();
    return 0;
}

异常安全的移动赋值操作符

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#include <iostream>
#include <string>
#include <stdexcept>

// 异常安全的移动赋值实现
class SafeResourceManager
{
private:
    int* data;
    size_t size;
    std::string name;
    
public:
    SafeResourceManager(const std::string& n = "unnamed", size_t s = 0)
        : name(n), size(s), data(nullptr)
    {
        if (size > 0)
        {
            data = new int[size];
            for (size_t i = 0; i < size; ++i)
            {
                data[i] = static_cast<int>(i + 1);
            }
        }
        std::cout << "Constructed: " << name << std::endl;
    }
    
    // 拷贝构造函数
    SafeResourceManager(const SafeResourceManager& other)
        : name(other.name + "_copy"), size(other.size), data(nullptr)
    {
        if (size > 0)
        {
            data = new int[size];
            std::copy(other.data, other.data + size, data);
        }
        std::cout << "Copy constructed: " << name << std::endl;
    }
    
    // 移动构造函数
    SafeResourceManager(SafeResourceManager&& other) noexcept
        : data(other.data), size(other.size), name(std::move(other.name))
    {
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move constructed: " << name << std::endl;
    }
    
    // 异常安全的拷贝赋值操作符(copy-and-swap idiom)
    SafeResourceManager& operator=(const SafeResourceManager& other)
    {
        std::cout << "Copy assignment: " << name << " = " << other.name << std::endl;
        
        if (this != &other)
        {
            SafeResourceManager temp(other); // 可能抛出异常
            swap(temp); // 不抛出异常的交换
        }
        return *this;
    }
    
    // 移动赋值操作符(强异常安全保证)
    SafeResourceManager& operator=(SafeResourceManager&& other) noexcept
    {
        std::cout << "Move assignment: " << name << " = " << other.name << std::endl;
        
        if (this != &other)
        {
            // 使用swap确保异常安全
            SafeResourceManager temp(std::move(other));
            swap(temp);
        }
        return *this;
    }
    
    // 交换函数(不抛出异常)
    void swap(SafeResourceManager& other) noexcept
    {
        std::swap(data, other.data);
        std::swap(size, other.size);
        std::swap(name, other.name);
    }
    
    ~SafeResourceManager()
    {
        delete[] data;
        std::cout << "Destroyed: " << name << std::endl;
    }
    
    void print() const
    {
        std::cout << "SafeResourceManager '" << name << "': size=" << size;
        if (data && size > 0)
        {
            std::cout << ", first element=" << data[0];
        }
        std::cout << std::endl;
    }
    
    const std::string& getName() const { return name; }
    size_t getSize() const { return size; }
    bool hasData() const { return data != nullptr; }
};

// 全局swap函数(支持ADL)
void swap(SafeResourceManager& a, SafeResourceManager& b) noexcept
{
    a.swap(b);
}

void ExceptionSafetyDemo()
{
    std::cout << "=== Exception Safety Demo ===" << std::endl;
    
    try
    {
        SafeResourceManager rm1("safe1", 5);
        SafeResourceManager rm2("safe2", 3);
        
        rm1.print();
        rm2.print();
        
        // 移动赋值(异常安全)
        rm2 = std::move(rm1);
        
        std::cout << "After safe move assignment:" << std::endl;
        rm1.print();
        rm2.print();
        
        // 测试swap
        std::cout << "\nTesting swap:" << std::endl;
        SafeResourceManager rm3("swap_test1", 7);
        SafeResourceManager rm4("swap_test2", 9);
        
        rm3.print();
        rm4.print();
        
        swap(rm3, rm4);
        
        std::cout << "After swap:" << std::endl;
        rm3.print();
        rm4.print();
        
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
}

// 性能比较:拷贝赋值 vs 移动赋值
void PerformanceComparisonDemo()
{
    std::cout << "\n=== Performance Comparison Demo ===" << std::endl;
    
    const size_t iterations = 10000;
    const size_t objectSize = 1000;
    
    // 测试拷贝赋值性能
    auto start = std::chrono::high_resolution_clock::now();
    
    SafeResourceManager copyTarget("copy_target", objectSize);
    for (size_t i = 0; i < iterations; ++i)
    {
        SafeResourceManager source("source_" + std::to_string(i), objectSize);
        copyTarget = source; // 拷贝赋值
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto copyTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    // 测试移动赋值性能
    start = std::chrono::high_resolution_clock::now();
    
    SafeResourceManager moveTarget("move_target", objectSize);
    for (size_t i = 0; i < iterations; ++i)
    {
        SafeResourceManager source("source_" + std::to_string(i), objectSize);
        moveTarget = std::move(source); // 移动赋值
    }
    
    end = std::chrono::high_resolution_clock::now();
    auto moveTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "Copy assignment time: " << copyTime.count() << " ms" << std::endl;
    std::cout << "Move assignment time: " << moveTime.count() << " ms" << std::endl;
    std::cout << "Speedup: " << (double)copyTime.count() / moveTime.count() << "x" << std::endl;
}

// 移动赋值的最佳实践
void BestPracticesDemo()
{
    std::cout << "\n=== Best Practices Demo ===" << std::endl;
    
    std::cout << "Move assignment operator best practices:" << std::endl;
    std::cout << "1. Always check for self-assignment (this != &other)" << std::endl;
    std::cout << "2. Mark as noexcept when possible" << std::endl;
    std::cout << "3. Clean up existing resources before moving" << std::endl;
    std::cout << "4. Leave moved-from object in valid state" << std::endl;
    std::cout << "5. Return *this for chaining" << std::endl;
    std::cout << "6. Consider using swap for exception safety" << std::endl;
    std::cout << "7. Implement alongside move constructor" << std::endl;
    
    // 演示正确的使用模式
    std::cout << "\nCorrect usage patterns:" << std::endl;
    
    SafeResourceManager rm1("pattern1", 5);
    SafeResourceManager rm2("pattern2", 3);
    SafeResourceManager rm3("pattern3", 7);
    
    // 链式赋值
    rm3 = rm2 = std::move(rm1);
    
    std::cout << "After chained move assignment:" << std::endl;
    rm1.print();
    rm2.print();
    rm3.print();
    
    // 条件移动
    bool shouldMove = true;
    SafeResourceManager conditional("conditional", 4);
    SafeResourceManager target("target", 2);
    
    if (shouldMove)
    {
        target = std::move(conditional);
    }
    else
    {
        target = conditional;
    }
    
    std::cout << "After conditional move:" << std::endl;
    conditional.print();
    target.print();
}

int main()
{
    ExceptionSafetyDemo();
    PerformanceComparisonDemo();
    BestPracticesDemo();
    return 0;
}

总结

  1. 移动赋值操作符基础T& operator=(T&& other) noexcept
  2. 关键实现要点
    • 检查自赋值:if (this != &other)
    • 清理现有资源:delete[] m_Buffer
    • 转移资源:窃取源对象的资源
    • 重置源对象:置于有效但未指定状态
    • 返回*this:支持链式赋值
  3. 异常安全
    • 标记为noexcept(如果可能)
    • 使用copy-and-swap idiom
    • 确保强异常安全保证
  4. 性能优势
    • 避免昂贵的资源拷贝
    • 减少内存分配和释放
    • 提高大对象赋值效率
  5. 最佳实践
    • 与移动构造函数一起实现
    • 处理自赋值情况
    • 保持异常安全
    • 遵循Rule of Five
  6. 应用场景
    • 容器元素重新赋值
    • 大对象的高效交换
    • 资源管理类的优化
    • 函数返回值优化
updatedupdated2025-09-202025-09-20