加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 对象切片如何导致内存损坏?

发布时间:2020-12-16 09:59:03 所属栏目:百科 来源:网络整理
导读:C专家 D语言创建者 Walter Bright说: The slicing problem is serious because it can result in memory corruption,and it is very difficult to guarantee a program does not suffer from it. To design it out of the language,classes that support in
C专家& D语言创建者 Walter Bright说:

The slicing problem is serious because it can result in memory
corruption,and it is very difficult to guarantee a program does not
suffer from it. To design it out of the language,classes that support
inheritance should be accessible by reference only (not by value). The
D programming language has this property.

如果某人通过给出一个C示例来解释它会更好,其中对象切片问题导致内存损坏? D语言如何解决这个问题?

解决方法

考虑

class Account
{
    char *name = new char[16];

    public: virtual ~Account() { delete[] name; }
    public: virtual void sayHello() { std::cout << "Hello Basen"; }

};

class BankAccount : public Account
{
    private: char *bankName = new char[16];
    public: virtual ~BankAccount() override { delete[] bankName; }
    public: virtual void sayHello() override { std::cout << "Hello Derivedn"; }

};

int main()
{
    BankAccount d;

    Account a1 = d; // slicing
    Account& a2 = d; // no slicing

    a1.sayHello(); // Hello Base
    a2.sayHello(); // Hello Derived

}

当Account :: ~Account而不是BankAccount :: ~BankAccount运行时,a1将泄漏bankName,因为它无法调用多态行为.正如为什么这么具体,它已经被大大解释了here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读