Is the code correct from the viewpoint of memory allocation?
#include <iostream>
using namespace std;
class A {
private:
    int x;
public:
    A():x(10){}
};
A &foo()
{
    return *(new A); //1
}
int main()
{
    A &a=foo();//2
    delete &a; //3
    return 0;
}
Explanation
The code is correct: the delete operator releases the memory allocated in the foo() function. In line 1 the pointer is dereferenced to return the reference to the object, in line 2 the object is returned, in line 3 the address of the released area is passed to the operator delete.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes