I have a class
class Foo
{
public:
char* ptr;
Foo() { ptr=new char [10]; }
~Foo() { delete [] ptr; }
};
I have learnt that returning an object of this class is not possible as the dynamically allocated pointer is delete
'ed and creates a dangling pointer in the calling function
So how can I return An object of this class??
Foo Bar ()
{
Foo obj;
return obj;
}
Can it be solved by adding a copy constructor
Foo::Foo(const Foo& obj)
{
ptr = new char [10];
for( int i = 0 ; i < 10 ;++i )
ptr [i] = obj.ptr[i];
}
And the function as
Foo Bar ()
{
Foo obj;
return Foo(obj); //invokes copy constructor
}
Note These are just representation of the actual class I want and is not created according to recommended standards (ie. Please don't tell me to use std::string
or std::vector
).