Search code examples
c++referencereturn-by-reference

deleting reference to dereferenced int


Even though the following piece of code compiles and runs fine i want to know if it is a valid c++ code?

int main()
{
        int *i= new int;
        cout<<*i;

        int &ref=*i;
        cout<<ref;

        delete &ref; //Especially is this statement valid?
        return 0;
}

If it is valid then this must also be valid :

int& getInt() {
    int* i = new int;
    return *i;  // OK?
}
int main(){
    int& myInt = getInt(); // these two lines are same as shown in the example above ?
    delete &myInt;   //is this OK too?
}

Solution

  • It's correct code and it will work on all platforms and compilers.

    However, it's probably not best practice as the reference is usually used when the called party retains the ownership of the object.