What are sideeffects in this code?

1
2
3
4
5
6
int main()
{
	int& test = *new int;
	delete& test;
	return 0;
}


are there some sideeffects by using this approach?
or why would that be bad approach?

thanks.
Last edited on
There are no side effects or undefined behaviour as far as the program is concerned. delete is invoked on a pointer returned by new, invoked only once, and the object is not accessed after that.

If you try to use the variable test after delete , the results would be unpleasant.

There may be terrible side effects on programmers who write this kind of code, though.

A suggestion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    int* p = new int(100) ;
       
    {
        int& test = *p ;
        // use test
    }
	
    delete p ;
    p = nullptr ;
        
     // ...

}


Using a std::unique_ptr<> would be even better.
Last edited on
Well, now I'm curious. What is wrong with this code? XD
It violates the the principle of least surprise. http://en.wikipedia.org/wiki/Principle_of_least_astonishment
nice example :D
thanks.
Topic archived. No new replies allowed.