用指针返回类对象

returning a class object with a pointer

本文关键字:对象 返回 指针      更新时间:2023-10-16

我有一个类

class Foo
{
    public:
    char* ptr;
    Foo()  { ptr=new char [10]; }
    ~Foo()  { delete [] ptr;  }
};

我了解到,由于动态分配的指针为 delete'ed,返回该类的对象是不可能的

那么我如何返回此类的对象??

Foo Bar ()
{
    Foo obj;
    return obj;
}

可以通过添加复制构造函数来解决它

Foo::Foo(const Foo& obj)
{
    ptr = new char [10];
    for( int i = 0 ; i < 10 ;++i )
        ptr [i] = obj.ptr[i];
} 

和功能为

Foo Bar ()
{
    Foo obj;
    return Foo(obj);     //invokes copy constructor
}

注意这些只是我想要的实际类的表示,并且不是根据建议的标准创建的(即。请不要告诉我使用std::stringstd::vector)。

那么我如何返回此类的对象??

您需要实现正确管理内存的复制构造函数和复制分配运算符。

// Copy constructor
Foo(Foo const& copy) : ptr(new char[strlen(copy.ptr)+1])
{
  strcpy(ptr, copy.ptr);
}
// Copy assignment operator
Foo& operator=(Foo const& rhs)
{
   // Don't do anything for self assignment
   if ( this != &rhs )
   {
      delete [] ptr;
      ptr = new char[strlen(rhs.ptr)+1]);
      strcpy(ptr, rhs.ptr);
   }
   return *this;
}

如果ptr始终将是10 char s的数组,则需要重新考虑复制构造函数和复制分配。

// Copy constructor
Foo(Foo const& copy) : ptr(new char[10])
{
  memcpy(ptr, copy.ptr, 10);
}
// Copy assignment operator
Foo& operator=(Foo const& rhs)
{
   // Don't do anything for self assignment
   if ( this != &rhs )
   {
      memcpy(ptr, rhs.ptr, 10);
   }
   return *this;
}