模拟虚拟副本构造函数

Simulate a virtual copy constructor

本文关键字:构造函数 副本 虚拟 模拟      更新时间:2023-10-16

我是c++的新手,只是通过看书来学习。所以这个问题可能有点愚蠢。这是我的程序:

#include <iostream>
using namespace std;
class Fish
{
public:
    virtual Fish* Clone() = 0;
};
class Tuna : public Fish
{
public:
        Tuna(const Tuna& SourceTuna)
    {
        cout << "Copy Constructor of Tuna invoked" << endl;
    }

    Tuna* Clone()
    {
        return new Tuna(*this);
    }
};

我对有疑问

return new Tuna(*this);

首先,为什么复制构造函数返回Tuna的指针?通常,调用复制构造函数会直接返回一个复制的实例。例如:

class Student
{   
public:
    Student(){}
    Student(const Student& Input) { cout << "Copy Ctor Invokedn"; }
};
int main()
{
    Student a;
    Student b(a);
    return 0;
}

根据我的理解,Student b(a);所做的是复制一个名为b的实例。那么,为什么new Tuna(*this)不返回实例而不是指针呢?

第二,为什么这是重点,即。论点中提供的*this?根据我的理解,this是一个指向当前对象的指针,这意味着*this是指向当前对象指针的指针。我尝试使用int来模拟这种情况。

// The input argument is the same as a copy constructor
int SimulateCopyConstructor(const int& Input){ return 0; }
void main()
{
    int a = 10;     // a simulate an object
    int* b = &a;    // b is a pointer of object a, which simulate "this"
    int** c = &b;   // c is a pointer to pointer of object a, which simulate of "*this"
    SimulateCopyConstructor(a); // It can compile
    SimulateCopyConstructor(b); // cannot compile
    SimulateCopyConstructor(c); // cannot compile
}

我认为将(*this)发送到复制构造函数与上面的情况c类似。但它不会编译。那么它是如何工作的呢?

Student b(a);

不返回Student对象。它声明它,并指示编译器在堆栈上分配的新对象上调用复制构造函数。

new Student(a);

这确实返回了一个指向新Student对象的指针,因为operator new确实返回了。其中(a)指示编译器在new分配的对象上调用复制构造函数。

然而,如果你有一个功能可以做到这一点:

Student foo(){ return Student(a); }

这将在堆栈上创建一个新的Student对象,调用复制构造函数,然后从函数返回结果对象。