以下情况会导致内存泄漏吗?如果是,我该如何解决这个问题?我应该在类中使用指针Base
(即Structure* var
)并在析构函数中删除它吗?
如果情况 2 不会导致内存泄漏,会发生什么Structure(0,0)
?它立即被创建并被销毁还是发生了其他事情?
情况1 :
struct Structure
{
int a;
int b;
Structure() { a=1; b=2; }
Structure(int num1, int num2) : a(num1), b(num2){}
};
class Base
{
private:
Structure var;
public:
Base(Structure structure)
{
var = structure;
}
};
class Derived : public Base
{
public:
Derived(bool boolean) : Base(boolean ? *(new Structure(0,0)) : *(new Structure(10,10))){}
};
int main()
{
Derived derived(true);
}
案例2:
struct Structure
{
int a;
int b;
Structure() { a=1; b=2; }
Structure(int num1, int num2) : a(num1), b(num2){}
};
class Base
{
private:
Structure var;
public:
Base(Structure structure)
{
var = structure;
}
};
class Derived : public Base
{
public:
Derived(bool boolean) : Base(boolean ? Structure(0,0) : Structure(10,10)){}
};
int main()
{
Derived derived(true);
}