简体   繁体   中英

is it good to create same object name many times c++

I have 4 building, each building has ten apartments. I created a class for each unit. class unit

to create an object, I need to parameters unit myunit(int building, int apartments)

at the beginning of the program, I need to create an object for each unit and add them to vector, which way is better to do that

the first way, I got Error operand type are: unit = unit *

int main()
{
    int building[4] = {1,2,3,4 };
    int apts[10]  = {1,2,3,4,5,6,7,8,9,10 };
    vector<unit > units(40);
    int vectorCounter = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
            // I got error in the line below.operand type are:unit = unit*
            units[vectorCounter++] = new unit (building[i], apts [j]);  
        }
    }

second way: create the same object name but different parameters

int main()
{
    int building = {1,2,3,4 };
    int apts  = {1,2,3,4,5,6,7,8,9,10 };
    vector<unit > units(40);
    int vectorCounter = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
        unit myunit(building[i], apts [j])   ;
            units[vectorCounter++] = myunit ;
        }
    }

third way : same as second way just add the destructor

int main()
{
    int building = {1,2,3,4 };
    int apts  = {1,2,3,4,5,6,7,8,9,10 };
    vector<unit > units(40);
    int vectorCounter = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
            unit myunit(building[i], apts [j])     ;
            units[vectorCounter++] = myunit ;
        ~unit() ;   
        }
    }

which way is better and why I got an error in the first way

First of all, your are not really creating an array when you wrote int building = {1,2,3,4 };

It should be int building[] = {1,2,3,4 };

The compile error is due to your vector is holding on to unit object but you are trying to assign a pointer to it. In your first method, you might want to let the vector store unit *

Your second way is okay, but the third way is wrong, destructors are not called this way and you should not manually call destructor, the compiler will do it for you when it leave your for loop scope.

In my opinion, Best is really dependent on what way do you want to use your vector, the fastest and safest method would be the second method, it use stack allocation and it is extremely fast and safe (no need to manually call delete). It is also cache friendly since everything is sequential in the memory, traversing thru all the units is fast.

Why should C++ programmers minimize the use of new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM