gpt4 book ai didi

c++ - 在派生类中使用基类 Copy CTOR

转载 作者:可可西里 更新时间:2023-11-01 17:44:11 28 4
gpt4 key购买 nike

我知道有很多关于这个主题的帖子,但我找不到任何帖子来完全回答我的问题。

假设我有一个基类和一个派生类,我为它实现了一个 CCtor 和一个赋值运算符,如下所示:

class Base {
char * name;
....
Base(const Base& other) :name(nullptr) { *this = other }
void operator=(const Base& other) { ... Deep copy of name }
}


class Derived : public Base {
....
Derived(const Derived& other) { *this = other ; }
void operator=(const Derived& other) {
Base::operator=(other);
.....
}

现在我对这个设计有一些疑问。

  1. 这是适合这种情况的设计吗?
  2. 如果我有第三个类,介于基类和派生类之间,但它只包含基本类型,我应该在哪里复制它们?例如。使用第二类的默认赋值运算符? build 一个新的?只在第三层复制它们?
  3. 我可以类似地在派生类 CCtor 中调用基类 CCtor,而不是赋值运算符。有什么不同?如果我将它们放在两种方法中,它会尝试复制值两次吗?

编辑:澄清一下,设计是我在项目中得到的。我有指针,所以我必须使用深拷贝。

最佳答案

Is this the right design for the situation?

不,通常不会。更惯用的方法是停止手动管理内存,如 char* name 并使用 std::string 或其他可以做正确事情的类型:

Class Base {
std::string name;
....
Base(const Base& other) = default;
Base& operator=(const Base& other) = default;
};

(请注意,赋值运算符应返回对类的引用,而不是 void)。

或者将内存管理封装在专门为此目的设计的类中(但 std::string 已经是那种类型)。

如果你真的真的需要用愚蠢容易出错的方式来做,那么实现你的复制构造函数来进行复制:

    Base(const Base& other) { / * deep copy of name */ }

然后将赋值实现为 copy-and-swap :

    Base& operator=(const Base& other)
{
Base tmp(other);
this->swap(tmp);
return *this;
}

这意味着您需要一个廉价的、不会抛出的 swap(Base&) 成员函数。

无论如何,派生类型的复制构造函数都是愚蠢的。您有一个正确的基类复制构造函数,因此它应该是:

Derived(const Derived& other) : Base(other) { }

并且赋值可以使用基础赋值:

Derived& operator=(const Derived& other)
{
Base::operator=(other);
return *this;
}

但是手动编写这些是不必要的,你可以只默认它的复制操作,无论如何都会做正确的事情:

class Derived : public Base {
public:
Derived(const Derived&) = default;
Derived& operator=(const Derived& ) = default;

If i have a third class, between the base and the derived class, but it only contains primitive types, where shoud I copy them ? E.G. use the default assignment operator of the second class ? build a new one? only copy them on the third level ?

您还应该使用 = default 定义该类的复制构造函数和赋值运算符。一旦您使 Base 可以安全地以正确的行为进行复制,编写其他类来使用它就很简单了。默认行为将做正确的事。如果您需要对动态分配的内存等未由 RAII 类型正确管理的内容进行特殊处理,则只需手动定义这些操作。

I could similary call the base class CCtor inside the derived class CCtor, instead of the assignment operator. What's the difference?

如果你想复制构造,那么使用复制构造函数,而不是赋值。为工作使用正确的函数。

关于c++ - 在派生类中使用基类 Copy CTOR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50607137/

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