模拟一个虚拟拷贝构造函数

Simulate a virtual copy constructor

我是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);

首先,为什么拷贝构造函数return是Tuna的指针? 通常,调用复制构造函数将 return 直接复制一个实例。 例如:

class Student
{   
public:
    Student(){}
    Student(const Student& Input) { cout << "Copy Ctor Invoked\n"; }
};

int main()
{
    Student a;
    Student b(a);
    return 0;
}

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

其次,为什么是这一点,即。 *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);

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

new Student(a);

这确实 return 是指向新 Student 对象的指针,因为 operator new 确实如此。并且 (a) 指示编译器在 new.

分配的对象上调用复制构造函数

但是,如果您有一个函数可以执行此操作:

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

这将在堆栈上创建一个新的 Student 对象,调用复制构造函数,然后 return 从函数中生成对象。