C++ Dynamic vs Stack Objects and How to Use Them [

2019-10-04 23:16发布

Follow-Up: Please head over to this question where there are actually some useful answers.

标签: c++ stack heap
3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-10-04 23:52

Instead of objects, think of "simpler" types. Would you do this:

void create() {
    int *obj1 = new int();
    int obj2;

    _obj1 = obj1;
    _obj2 = &obj2;
}

Would you think this would work? Clearly not. It's very simple. You can't pass out the pointer to an object allocated to the stack (and, as a rule of thumb, you shouldn't pass out the pointer to an object you have just allocated. If someone allocates an object he is responsable to free it)

查看更多
做自己的国王
3楼-- · 2019-10-04 23:58

A basic design principle of C++ is that you don't pay for what you don't use, so that C++ can be used to write highly optimized code. Stack allocation is more efficient, whatever your language.

查看更多
爷的心禁止访问
4楼-- · 2019-10-05 00:02

Heap objects per se are not wrong, failure to manage their lifetime is.

Stack objects have the property that their destructor will be called regardless of how the code leaves the function (exception, return value). Smart pointers exploit this to manage the lifetime of heap allocated objects (a happy medium?)

查看更多
登录 后发表回答