Home > OS >  C How to store object in arrays without them deleted
C How to store object in arrays without them deleted

Time:11-09

I want to seek help on this issue I encountered when learning C . I tried to store objects into an array directly, but realize the objects gets deconstructed right away. I could not figure out why exactly is this so.

#include <iostream>

class Thing{
    public:
    ~Thing(){
        std::cout<<"Thing destructing";
    }
};

int main(){
    Thing arr[1];
    arr[0] = Thing();
    int x;
    std::cin>>x;
};

CodePudding user response:

In this statement

arr[0] = Thing();

there is used the default copy assignment operator that assigns the temporary object created by this expression Thing() to the element of the array. After the assignment the temporary object is destroyed.

To make it more clear run this demonstration program.

#include <iostream>

class Thing
{
public:
    ~Thing()
    {
        std::cout<<"Thing " << i << " destructing\n";
    }
    
    Thing & operator =( const Thing & )
    {
        std::cout << "Thing " << i << " assigning\n";
        return *this;
    }
    
    Thing() : i(   n )
    {
        std::cout << "Thing " << i << " constructing\n";
    }

private:    
    size_t i;
    static size_t n;
};

size_t Thing::n = 0;

int main() 
{
    {
        Thing arr[1];
        arr[0] = Thing();
    }
    
    std::cin.get();
    
    return 0;
}

Its output is

Thing 1 constructing
Thing 2 constructing
Thing 1 assigning
Thing 2 destructing
Thing 1 destructing

CodePudding user response:

Assuming you don't know already.

Smart-Pointer

#include <memory>

// ...

int main() {
    std::shared_ptr<Thing> arr[1];
    arr[0] = std::shared_ptr<Thing>(new Thing());

    // ...

    // <-- Is automatically deleted around here.
}

Pointer

Not-Recommended; Using pointer would look like:

int main() {
    Thing *arr[1] = {};
    arr[0] = new Thing();

    int x;
    std::cin >> x;

    // WARNING: remember to manually delete.
    delete arr[0];
} // <-- BTW, you don't need semi-colon.
  • Related