在 C++ 中测试深/浅拷贝时析构函数无法解释的行为

瓦卡尔·艾哈迈德
class String
{
  private:
    char* ptr;
  public:
  
    String(const String& s1)
    {
       int len = strlen(s1.ptr);
       ptr = new char[len+1];
       strcpy(ptr,s1.ptr);
       
    }
    String(char* c)
    {
      int len = strlen(c);
       ptr = new char[len+1];
       strcpy(ptr,c);
       
    }
    ~String()
    { 
      cout<<"DELETING\n";
      delete[] ptr;
    }
    void display()
    {cout<<ptr;}
};

int main()
{
String s("Waqar"); String* s2  =&s;
String s1(s);
delete s2;
s1.display();

一直到倒数第二行都很好delete s2在调试时,它会抛出一个未知信号的错误,并且永远不会执行s1.display()作为一个菜鸟,我在 C++ 中测试深拷贝和浅拷贝概念,因此写了这个垃圾。我哪里做错了?

沙丘

s2指向s. 它是一个指针,根本不是一个副本(浅或其他)。它从未被分配任何内存new因此,当您尝试删除时s2,您是在要求程序释放堆栈上不受 new/delete 管理的内存。delete s2在这种情况下不要。这是一个错误。你的析构函数在这里没有错。

这是一个示例程序,详细说明了如何以及何时调用析构函数的不同点,并且仅delete使用new.

// declare `copy`, but do not initialise it just yet. We want to
// initialise it from `s` (which is not yet declared)
String* copy;
{
    // declare and initialise `s`, and copy "Wagner" into s.ptr
    String s("Wagner");
    // create a new String on the heap, initialised from `s`
    // this is a deep copy because of how you wrote String(String&)
    copy = new String(s);
    s.display();
    // `s` falls out of scope at the end of this block
    // this means that s.~String() is invoked
}
// `copy` is unaffected as it was declared in the outer scope, 
// and because it is a deep copy. Had it been a shallow copy
// then it would be broken as its `char* ptr` would not be valid
// any more.
copy->display();
// copy->~String() is invoked when copy is deleted
delete copy;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章