im trying to return a local object from a function
and i have this problem
if i return the locally created object it returns null
DString DString :: operator + (const char* param)
{
// Variable definition
int nSize = ( this->GetLength() + (strlen(param)));
// Create a new char array in the opropriate size
char* cstrNewString = new char[nSize + 1];
// Append data
strcpy(cstrNewString, this->_cstrString);
strcat(cstrNewString, (char*)param);
cstrNewString[nSize] = '\0';
// Create a new DString to return
DString dstNewData(cstrNewString);
// Clean up
delete[] cstrNewString;
// Return data
return (dstNewData); // Null!
if i do the same exact thing only creating a new object in the return line such as this:
DString DString :: operator + (const char* param)
{
// Variable definition
int nSize = ( this->GetLength() + (strlen(param)));
// Create a new char array in the opropriate size
char* cstrNewString = new char[nSize + 1];
// Append data
strcpy(cstrNewString, this->_cstrString);
strcat(cstrNewString, (char*)param);
cstrNewString[nSize] = '\0';
// Create a new DString to return
DString dstNewData(cstrNewString);
// Clean up
delete[] cstrNewString;
// Return data
return (DString(dstNewData.ToCharArray())); // Not null, returns correctly!
it returns correctly.. why is it doing this and how can i fix this ?
How is your copy constructor defined? In the first case, the copy
constructor is called; in the second no. You don’t show us any of the
essential code for
DString, but given the apparent semantics, it seemsalmost certain that the compiler generated copy constructor will not
do the right thing. If you’re
DStringcontains a dynamicallyallocated pointer (and I don’t see how it could be otherwise), which is
deleted in the destructor, the copy constructor must make a deep copy.