c++ - Stack or Heap in inderect heap allocation -


is funcvar on stack or heap in scenario 1?

i'm asking because suspect is, , hence may way things minimize memory leaks. say, may better give things auto allocation locations , place code @ higher levels on heap put things @ lower levels on heap indirectly in scenario 1.

in scenario 2, delete may never called. using code in scenario 1, hope minimize (not eliminate) issues in scenario 2.

scenario 1

class test{     int memvar = 1;      void func(){         int funcvar = 2;         someclass::somefuncthatcouldcrash();     } };  test* t = new test(); 

scenario 2

class test{     int memvar = 1;      void func(){         int* funcvar = new int(2);         someclass::somefuncthatcouldcrash();         delete funcvar;   //may not free due crash in line above;     } };  test t;  //or test* t = new test() 

in scenario 1 funcvar (assuming int funcvar = 2) on stack when func() called , in scenario 2 on heap. correct, if somefuncthatcouldcrash threw exception never deleted.

also, in scenario 2 delete funcvar , return it.. that's no good. in case returning pointer when return type regular int.

in c++11 don't ever want handle raw new , delete. basically, should variable on stack. if need heap allocations, use vector local variable on stack manages heap allocations internally. way, when vector leaves scope cleans without ever having call delete. known raii (resource allocation initialization) if want further.

in case need pointer object (such holding polymorphic object via base-class pointer, or creating instances of large classes in general) want std::unique_ptr create local variable responsible calling delete on object created. under rarer circumstances may need std::shared_ptr can , why you'd need if want.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -