I know that I can’t get a reference of a local var. such as:
int& func1()
{
int i;
i = 1;
return i;
}
And I know that this is correct, but I have to delete it after calling func2()
int* func2()
{
int* p;
p = new int;
*p = 1;
return p;
}
int main()
{
int *p = func2();
cout << *p << endl;
delete p;
return 0;
}
If the function is like this:
MyClass MyFunction()
{
return new MyClass;
}
MyClass’s whole definition is:
class MyClass
{
public:
MyClass() : num(1){}
MyClass(MyClass*) : num(10){}
int num;
};
Will this cause memory leak?
How should I avoid it?
the function returns an object not a pointer, so how can I delete it?
PS: the code comes from the book “Ruminations on C++” Chapter 10.
the original code is:
Picture frame(const Pictrue& pic)
{
// Picture has a constructor Picture(*P_Node)
// Frame_Pic derives from P_Node
// So the constructor Picture(*P_Node) will implicitly convert Frame_Pic to Picture.
return new Frame_Pic(pic);
}
With your updated
MyClassthat has the pointer constructor, I suppose you should write:That happens to be exception-safe, since the constructor of MyClass can’t throw, but as a general rule you really shouldn’t ever call
newwithout putting the result straight into a smart pointer:It’s a fairly absurd situation anyway – if you’re going to return by value, there’s no reason to call
newat all:And since the value of the pointer isn’t even used by the pointer constructor, you could just as well write:
In the original code your quote from the book, I guess that the class
Picturehas a data member of typeP_Node*, in which it stores the pointer value, and callsdeleteon that pointer in its destructor. Hopefully the author also does something about the copy constructor and copy assignment operator ofPicture, to prevent a double-free after the copy. I don’t have the book, so I can’t check my guess, but the code forPictureshould show how it’s done.[Edit: oh, that’s one of the books by Koenig and Moo. They are (more than) competent, so pretty certainly their
Pictureclass handles the resource correctly. If it doesn’t, it’s because it’s a deliberate example of Doing It Wrong.]