I have functions that return an object, but I’m confused that should I return the object itself or a pointer to the object?
Here is an example of my function:
CImage CDocument::AddImage(string Name, string fileName)
{
CImage img = CImage();
img.Name = Name;
img.Path = fileName;
img.IwImage = Iw2DCreateImage(&fileName[0]);
Images.push_back(&img);
return img;
}
Is this correct or should I return the pointer to the object:
CImage * CDocument::AddImage(string Name, string fileName)
{
CImage * img = new CImage();
img->Name = Name;
img->Path = fileName;
img->IwImage = Iw2DCreateImage(&fileName[0]);
Images.push_back(img);
return img;
}
Although the last code don’t compile correctly because I got this error:
error C2440: 'initializing' : cannot convert from 'CImage' to 'CImage *'
I think this might be very simple question. I’m very new to c++ so bear with me.
There are multiple problems in this code, the basic difference to understand when coding in C++ is between stack allocation and heap allocation. When you do
CImage img = CImage();the object is created on stack. This object is destroyed automatically when the function ends. Now, if you return a pointer to this object, the caller will be getting a pointer to an invalid memory location as the object is already destroyed. You are also pushing the address of this object into the vector, which again will be invalid once the function ends. Same problem is there with thefileNamealso.To solve this, you need to allocate memory from heap so that object is not destroyed when the function ends. You can allocate objects on heap using
newin C++. So your code will becomeCImage* pImage = new CImage();. Note that in this case it is your responsibility to release the memory usingdelete. So you can change your function to returnCImage*using this technique. You can also push this pointer into the vectorImages. Note that to release the memory allocated for theCImageobects, you need to loop through theImagesvector and call explicitly calldeleteon each pointer.A better approach would be to use smart pointer such as
std::shared_ptrin this case which will manage the calling ofdeleteautomatically for you.