Consider following code.
#include <stdio.h>
using namespace std;
constexpr size_t TOTAL = 2;
class thing
{
private:
inline static size_t NEXT_ID = 0;
size_t id;
public:
thing() : id(NEXT_ID++)
{
printf("Thing %zd created.\n", this->id);
}
~thing()
{
printf("Thing %zd destroyed.\n", this->id);
}
};
class container
{
private:
inline static size_t NEXT_ID = 0;
size_t id;
thing* things;
public:
container() : id(NEXT_ID++)
{
this->things = new thing[TOTAL];
printf("Container %zd created.\n", this->id);
}
~container()
{
delete[] this->things;
printf("Container %zd destroyed.\n", this->id);
}
thing& at(size_t idx) // this is the important method
{
return this->things[idx];
}
};
int main()
{
container c;
c.at(0) = thing(); // here is the problem
return 0;
}
The output is something I didn't expect.
Thing 0 created.
Thing 1 created.
Container 0 created.
Thing 2 created.
Thing 2 destroyed.
Thing 1 destroyed.
Thing 2 destroyed.
Container 0 destroyed.
I know that Thing 2
was a temporary object, that's why it was destroyed twice. I have a few questions about what happened to Thing 0
.
- Why wasn't
Thing 0
destroyed? - Will there be a memory leak?
- Do I have to destroy
Thing 0
somehow or was it overwritten successfully?