我正在研究五法则及其表亲(四法则和 1/2、复制和交换成语、朋友交换功能)。
我在测试课上实施了四和 1/2 规则。它编译得很好。我的实施中是否有任何隐藏的错误?
我特别关注存储在我在复制构造函数中移动的m_unorederd_map属性中的 unique_ptrs,因为它们无法被复制。这是在类中处理 unique_ptrs 的正确方法吗?
某个类.h
#ifndef SOMECLASS_H
#define SOMECLASS_H
#include "someotherclass.h"
#include <QString>
#include <QStringList>
#include <memory>
#include <string>
#include <unordered_map>
class SomeClass
{
QString m_qstring;
std::unordered_map<std::string, std::unique_ptr<SomeOtherClass>> m_unordered_map;
int m_int;
std::string m_string;
QStringList m_qstringlist;
public:
SomeClass() = default;
// Rule of 5 (or Rule of 4 and 1/2)
// From https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom#3279550
~SomeClass() = default; // Destructor
SomeClass(SomeClass &other); // Copy constructor
SomeClass(SomeClass &&other); // Move constructor
SomeClass &operator=(SomeClass other); // Copy/Move assignment operator
friend void swap(SomeClass &first, SomeClass &second) // Friend swap function
{
using std::swap;
first.m_qstring.swap(second.m_qstring);
first.m_unordered_map.swap(second.m_unordered_map);
swap(first.m_int, second.m_int);
swap(first.m_string, second.m_string);
first.m_qstringlist.swap(second.m_qstringlist);
}
};
#endif // SOMECLASS_H
某类.cpp
#include "someclass.h"
// Copy constructor
SomeClass::SomeClass(SomeClass &other)
: m_qstring(other.m_qstring),
m_int(other.m_int),
m_string(other.m_string),
m_qstringlist(other.m_qstringlist)
{
// m_unordered_map holds unique_ptrs which can't be copied.
// So we move it.
m_unordered_map = std::move(other.m_unordered_map);
}
// Move constructor
SomeClass::SomeClass(SomeClass &&other)
: SomeClass()
{
swap(*this, other);
}
// Copy/Move assignment operator
SomeClass &SomeClass::operator=(SomeClass other)
{
swap(*this, other);
return *this;
}