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

对着背影说爱祢 提交于 2019-12-13 09:47:27

问题


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


回答1:


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)




回答2:


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?)




回答3:


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.



来源:https://stackoverflow.com/questions/5056226/c-dynamic-vs-stack-objects-and-how-to-use-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!