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;
};
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