gpt4 book ai didi

c++ - 语义略有不同的复制构造函数和赋值运算符中是否存在陷阱?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:21 27 4
gpt4 key购买 nike

请看下面的代码并告诉我它是否会在未来引起问题,如果是,如何避免它们。

class Note
{
int id;
std::string text;

public:
// ... some ctors here...

Note(const Note& other) : id(other.id), text(other.text) {}

void operator=(const Note& other) // returns void: no chaining wanted
{
if (&other == this) return;
text = other.text;
// NB: id stays the same!
}
...
};

简而言之,我希望复制构造函数创建一个对象的精确拷贝,包括它的(数据库)ID 字段。另一方面,当我分配时,我只想复制数据字段。但我有一些顾虑,因为通常复制构造函数和 operator= 具有相同的语义。

id 字段仅供 Note 及其 friend 使用。对于所有其他客户端,赋值运算符确实创建了一个精确拷贝。用例:当我想编辑笔记时,我使用复制构造器创建一个拷贝,对其进行编辑,然后在管理笔记的 Notebook 类上调用保存:

 Note n(notebook.getNote(id));
n = editNote(n); // pass by const ref (for the case edit is canceled)
notebook.saveNote(n);

另一方面,当我想创建一个与现有笔记内容相同的全新笔记时,我可以这样做:

 Note n; 
n = notebook.getNote(id);
n.setText("This is a copy");
notebook.addNote(n);

这种方法合理吗?如果不是,请指出可能的负面后果是什么!非常感谢!

最佳答案

如果您想要的语义与赋值运算符的预期不匹配,请不要使用它。相反,通过声明一个私有(private)的 operator= 来禁用它,并定义一个函数,其名称可以清楚地说明正在发生的事情,例如 copyDataFields

关于c++ - 语义略有不同的复制构造函数和赋值运算符中是否存在陷阱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2209935/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com