用指针返回类对象
returning a class object with a pointer
我有一个类
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::string
或std::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;
}
相关文章:
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?
- 从我的对象返回静态数组
- 将unique_ptr作为<Object>unique_ptr<常量对象返回>
- 从右值对象返回成员
- 视觉对象 返回 C++ 中的双精度值
- 为什么类型为 sf::Text 的对象返回不同的 getPosition().y 和 getLocalBounds().
- std::min_element 从类对象返回意外结果
- C++无效的对象返回语义
- const引用是否延长临时对象返回的临时对象的寿命
- 将 NULL 作为对象返回时未收到任何警告
- 如何在 C# 中从 com 对象返回数组(double[])
- 从重载运算符返回引用,并使用临时对象返回表达式
- Cin 对象返回值 c++
- 将变量作为类对象返回
- 使用可更改对象返回只读的最佳方法是什么
- 如何在Cython中从另一个包装对象返回包装的c++对象
- 当对象返回时,c++动态数组被清除
- 从带有动态字段的函数、对象返回
- 从堆栈上的匿名对象返回对*this的引用