c++ - Class members memory allocation -


my question theoretical. suppose have class

class a{ private:     int * a;     int b; private:     a(){       = new int[100];       b = 100;     }    ~a(){       delete [] a;     } } 

as far know if create object of type dynamically (a * = new a()) memory object allocate in heap , if use (a a) created on stack (a a). in case when object created on stack memory variable a allocated on heap , in case when allocated object on heap memory object b allocated on stack. first question me sure: right?

and second question more efficient store members of class in heap memory or stack memory eg?

class a{     private:         int * a;         int * b;     private:         a(){           = new int[100];           b = new int(100);         }        ~a(){           delete [] a;           delete b;         }     } 

when said efficient mean data class member storing near each other in memory in heap or stack (actually i'm not sure correct storing near each other).

first off there no heap or stack in c++. instead have automatic storage duration , dynamic storage duration. object automatic storage duration scoped object. when cope left automatically cleaned up. object dynamic storage duration on other hand not bound scope. lifetime ends when explicitly ended program (generally means calling delete).

now in a have 1 object stored automatic storage duration , b, , 1 dynamic storage duration ,a. means b live wherever a instance lives. a live within a instance memory points reside somewhere in memory not know where. when instance destroyed b automatically cleaned a required special handling in destructor otherwise memory leak. can visualize like

    +------+   +----------+ |   a->+---| 100 ints | |   b  |   +----------+ +------+ 

as far efficiency goes some programmer dude mentioned should not worry that. should use types fell right job. once have , running can profile find bottle neck is. if see many cache misses because of using pointers can @ trying localize data class itself.

i mention if find writting some_type* name = new/new[] should consider using std:unique_ptr<some_type>/std:unique_ptr<some_type[]> or std::vector<some_type>.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -