考虑以下代码。
#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;
}
输出是我没想到的。
Thing 0 created.
Thing 1 created.
Container 0 created.
Thing 2 created.
Thing 2 destroyed.
Thing 1 destroyed.
Thing 2 destroyed.
Container 0 destroyed.
我知道那Thing 2
是一个临时对象,这就是为什么它被摧毁了两次。我有几个关于发生了什么的问题Thing 0
。
- 为什么没有
Thing 0
被销毁? - 会不会有内存泄漏?
- 我必须以
Thing 0
某种方式破坏还是成功覆盖?