我无法将我的大脑围绕所有权和通过动作最大化性能。想象一下这组假想的类模拟 Excel 工作簿。
namespace Excel {
class Cell
{
public:
// ctors
Cell() = default;
Cell(std::string val) : m_val(val) {};
// because I have a custom constructor, I assume I need to also
// define copy constructors, move constructors, and a destructor.
// If I don't my understanding is that the private string member
// will always be copied instead of moved when Cell is replicated
// (due to expansion of any vector in which it is stored)? Or will
// it be copied, anyways (so it doesn't matter or I could just
// define them as default)
value() const { return m_val; }; // getter (no setter)
private:
std::string m_val;
}
class Row
{
public:
// ctors
Row() = default;
Row(int cellCountHint) : m_rowData(cellCountHint) {}
// copy ctors (presumably defaults will copy private vector member)
Row(const Row&) = default;
Row& operator=(Row const&) = default;
// move ctors (presumably defaults will move private vector member)
Row(Row&& rhs) = default;
Row& operator=(Row&& rhs) = default;
// and if I want to append to internal vector, might I get performance
// gains by moving in lieu of copying, since Cells contain strings of
// arbitrary length/size?
void append(Cell cell) { m_rowData.push_back(cell); };
void append(Cell &&cell) { m_rowData.push_back(std::move(cell)); };
private:
std::vector<Cell> m_rowData;
}
}
等等:
- 工作表类将包含行向量
- Workbook 类将包含 Worksheets 的向量
我觉得没有必要为 MWE 实现最后两个,因为它们实际上是 Row 的重复(我的假设是它们与 Row 的设计相同)。
我很难理解是否可以依赖默认值,或者我是否应该定义自己的移动构造函数(而不是保持默认值)以确保私有向量成员变量被移动而不是被复制,但这一切都非常令人困惑对我来说,我似乎只能找到一个除了内置类型成员之外什么都没有的类的过于简单化的例子。