在构造函数中动态分配新对象 [英] Dynamically allocating new object in constructor

查看:172
本文介绍了在构造函数中动态分配新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以给定这个简单的场景:

So given this simple scenario:

class A{
public:        
    A(){
        n = new int(10);
    }
    ~A(){
        delete n;
    }
    int* n;
};

int main(){
    A* a = new A();
}

这可能会导致堆损坏(一般问题),因为指针hasn没有完成分配,而我正在进行新的分配?

Can this cause heap corruption (problems in general), since a-pointer hasn't finished allocating, while I'm making a new allocation?

如果是这样,在堆构造函数中使用std :: vector也是禁止的,对吗?

If so, using std::vector inside heap constructors in also prohibited, right?

谢谢。

推荐答案

您的 a 指针已完成分配

新工作如下(过度简化)

New works as follows (oversimplified)


  • 分配

  • 建构

在您的情况下


  • 分配A

  • 构造A

    • 分配i​​nt

    • 构造int - 初始化

    这将忽略涉及例外的情况。

    This ignores cases involving exceptions..

    这篇关于在构造函数中动态分配新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆