你发现这个 C++ 有什么问题吗?代码?

发布于 2024-11-03 12:17:34 字数 422 浏览 3 评论 0原文

#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

我错了吗?

#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();
}

This programs,i have executed in Dev c++ and compiles and executes fine.
But i doubt this is not fine.Specially in the destructor where i say delete P

am i wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

东走西顾 2024-11-10 12:17:35

该代码在逻辑上很好(您所询问的 new/delete 部分),但在其他方面设计得很糟糕。

首先,如果class A拥有堆分配的intint的生​​命周期与class A对象的生命周期相同) )用 new 创建它是没有意义的,将其作为 A 类的成员变量会更有效。其次,您不应该将其公开 - 这会破坏封装并允许大量滥用。

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

不过,删除使用new分配的变量的部分完全没问题。

That code is logically fine (the part with new/delete you're asking about), but designed badly in other aspects.

First, if class A owns that heap-allocated int (int lives for as long as class A object lives) there's no point in creating it with new, it'd be much more efficient to make it a member variable of class A. Second, you shouldn't make it public - that breaks encapsulations and allows lots of abuse.

Finally, you still have copy constructor and assignment operator allowed and unimplemented, so any time a class object is copied you get shallow copy. You should either implement them appropriately or prohibit them.

The part where you delete a variable allocated with new is completely fine however.

病毒体 2024-11-10 12:17:35

我发现此代码有 4 个问题:

  • new 的两次使用
  • delete 的两次使用

可能是您剪下的精简代码在某种程度上缺乏原始实现,或者您来了来自一种一切都是新的语言,但其代码远非惯用的 C++。

惯用的重写:

#include<iostream>

class A
{
public:
  int p;

  ~A() { std::cout << "~A" << std::endl; } // force a flush with endl
};

int main(int argc, char* argv[])
{
  {
    A obj;
  } // for destruction to occur before getch

  // use streams instead of getch
  char a;
  std::cin >> a;

  // the signature says it returns an int...
  return 0;
}

I see 4 issues with this code:

  • two uses of new
  • two uses of delete

It may be that your reduced code snipped is somewhat lacking wrt the original implementation, or that you come from a language where everything is new'ed, but the code as is is far from being idiomatic C++.

The idiomatic rewrite:

#include<iostream>

class A
{
public:
  int p;

  ~A() { std::cout << "~A" << std::endl; } // force a flush with endl
};

int main(int argc, char* argv[])
{
  {
    A obj;
  } // for destruction to occur before getch

  // use streams instead of getch
  char a;
  std::cin >> a;

  // the signature says it returns an int...
  return 0;
}
毁虫ゝ 2024-11-10 12:17:35

正如 Sharptooth 指出的那样,在 dtor 中使用 delete 是完全有效的。 delete null 在 std 中定义为 noop。

但是,对于这样的事情,请考虑使用shared_ptr或类似的东西......

hth

Mario

As sharptooth pointed out, using delete in the dtor is completely valid. delete null is defined in the std as noop.

however, for things like this, consider using a shared_ptr or something similar...

hth

Mario

流年里的时光 2024-11-10 12:17:35

在这种情况下,您还需要定义自己的复制构造函数和赋值运算符(或将它们声明为私有以使类不可复制);默认的复制构造函数和赋值运算符执行浅复制。也就是说,它们复制指针,而不是指针的内容。因此,如果您这样做:

A x;
A y = x;

xpyp 都指向同一位置,因此当它们被破坏时,它们会尝试释放相同的内存,这会产生未定义的行为。

要解决此问题,请定义您自己的复制构造函数和复制 int 的赋值运算符:

class A
{
public:
        A() : p(new int) {}
        A(const A& obj) : p(new int(*obj.p)) {}
        ~A() { delete p; }
        A& operator=(const A& obj) { *p = *obj.p; }
private:
        int *p;
};

You also need to define your own copy constructor and assignment operator (or declare them as private to make the class as noncopyable) in this case; the default copy constructor and assignment operator do a shallow copy. That is, they copy the pointer, not the contents of the pointer. So if you do this:

A x;
A y = x;

Both x.p and y.p point to the same location, hence when they're destructed they try to free the same memory, which yields undefined behavior.

To fix this, define your own copy constructor and assignment operator that copies the int:

class A
{
public:
        A() : p(new int) {}
        A(const A& obj) : p(new int(*obj.p)) {}
        ~A() { delete p; }
        A& operator=(const A& obj) { *p = *obj.p; }
private:
        int *p;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文