模拟虚拟副本构造函数

时间:2015-07-20 15:18:05

标签: c++ pointers this 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);

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

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)没有返回实例而不是指针?

其次,为什么要这样,即。 *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类似。但它没有编译。那它是如何运作的?

1 个答案:

答案 0 :(得分:2)

Student b(a);

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

new Student(a);

这确实会返回指向新Student对象的指针,因为operator new会这样做。并且(a)指示编译器调用由new分配的该对象的复制构造函数。

但是,如果你有一个功能这样做:

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

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