Dynamically allocating new object in constructor

2019-02-27 11:12发布

So given this simple scenario:

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

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

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

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

Thank you.

3条回答
闹够了就滚
2楼-- · 2019-02-27 11:38

if "new" throw an exception then the object is not allocated (beware any allocation made BEFORE "new" need to be deallocated else you'll have a memory leach)..

Exceptions are thinked to be used as error system since constructor can't return a error code.

myclass::myclass()
{
    param1 = new type1(); //successfull
    try
    {
        param2= new type2(); //may fail
    }
    (...)
    {
        delete param1; //need to deallocate
    }
}

That's a bit overkill, I prefer to have no exceptions in constructors at all, some people make entire frameorks with constructors than can throw exceptions..

anyway any other bug in the allocator can cause:

segmentation fault (access out-of-range value)

heap corruption (overwrite data that is in memory range but that is not tecnically owned bythe object)

infinite loop (you need to abort the program externally or it will never exit the allocator).

Those are the mains problem that you can also have with normal code of course. The default allocator however will not give any problem, at least can throw a "out of memory" exception. if you not have enough ram.

查看更多
贼婆χ
3楼-- · 2019-02-27 11:39

There is no such thing as a "heap constructor", and no, you cannot corrupt the heap by newing memory inside a constructor of an object on the heap. The memory for the new A is fully allocated at the time A::A() is invoked. What you're doing is both correct and extremely common. Your constructor need never be concerned with whether the object being constructed is allocated on the stack or heap. Otherwise, pointers and classes would be pretty useless.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-27 11:55

Your a pointer has finished allocating.

New works as follows (oversimplified)

  • Allocate
  • Construct

So in your case

  • Allocate A
  • Construct A
    • Allocate int
    • Construct int - initialize
  • Finish Construct A

This ignores cases involving exceptions..

查看更多
登录 后发表回答