gpt4 book ai didi

c++ - 你看到这个 C++ 代码有什么问题吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:06 24 4
gpt4 key购买 nike

#include<iostream>
#include<conio.h>
using namespace std;
class A
{
public:
int *p;
A()
{
p =new int;
}

~A()
{
delete p; //Is this what i am doing is correct?
cout << "in A's destructor"<<endl;
}

};

int main()
{
A *obj=new A;
delete obj;
getch();
}

这个程序,我已经在 Dev c++ 中执行并且编译和执行都很好。但我怀疑这不是很好。特别是在我说 delete P

的析构函数中

我错了吗?

最佳答案

这段代码逻辑上没问题(你问的是 new/delete 的部分),但其他方面的设计很糟糕。

首先,如果 class A 拥有堆分配的 int(int 的生命周期与 class A 一样长) > object lives) 用 new 创建它没有意义,让它成为 class A 的成员变量会更有效率。其次,您不应该将其设为 public - 这会破坏封装并允许大量滥用。

最后,您仍然允许但未实现复制构造函数和赋值运算符,因此每次复制类对象时,您都会获得浅拷贝。您应该适本地实现它们或 prohibit them .

delete 分配给 new 的变量的部分完全没问题。

关于c++ - 你看到这个 C++ 代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5788330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com