参数化构造函数内的指针

问题描述 投票:1回答:1

我正在为类的构造函数中的指针指定一个指针。在析构函数中,我删除了一个成员变量指针。这意味着当调用析构函数时,也会删除作为参数传入的指针,但我无法理解为什么。我做了一小段代码来预览我的问题。

class IWrite {
public:
    virtual void write(string) = 0;
};

class Consolerite : public IWrite
{
public:
    void write(string myString)
    {
        cout << myString;
    }
};

class OutPut
{
public:
    OutPut(IWrite* &writeMethod)
    {
        this->myWriteMethod = writeMethod;
    }
    ~OutPut() { delete this->myWriteMethod; }

    void Run(string Document)
    {
        this->myWriteMethod->write(Document);
    }

private:
    IWrite* myWriteMethod = NULL;
};

int main()
{
    IWrite* writeConsole = new Consolerite;
    OutPut Document(writeConsole);
    Document.Run("Hello world");
    system("pause");
}

当程序退出时,IWrite * writeConsole被删除但我无法理解原因。有人可以帮助我理解这一点。谢谢。

c++ pointers
1个回答
2
投票

您不是“删除指针”,而是删除此指针指向的对象(即使用new Consolerite创建的对象)。并且由于指针传递并且成员字段指针指向同一个对象,一旦在任何对象上使用delete,它们都将变为无效。

此程序还有未定义的行为,因为您使用指向没有virtual析构函数的基类的指针删除对象。

© www.soinside.com 2019 - 2024. All rights reserved.