return a local reference

Hi,

I'm not new to C++, been programming in it for years but I cam across something today I'd never tried.

I was messing around with a library I wrote to increase it's performance, and to do this I changed some parameters to be references. This worked great but after looking up some info on the best way to do it I came across this on a site:
1
2
3
4
5
6
int& New()
{
	int newInt = 777;
	int& returnref= newInt;
	return returnref;
}

And I was just wondering, is this in anyway safe to use? Will the newInt not be deallocated upon return leaving only the reference and no way to know what is actually in memory that the given location?

meaning it is the same as doing:
1
2
3
4
5
int& New()
{
	int newInt = 777;
	return *newInt;
}

but without getting a compiler warning?

Or am I looking at this the wrong way?
1
2
3
4
5
6
7
int& New()
{
	int newInt = 777;
	return *newInt;    
}




must be a pointer to newInt.
newInt is destroyed at the end of the block and all pointers or references to it become invalid.
Yes this I know, but will it still be destroyed if there is a reference to it?

What I'm trying to ask is, do references keep a memory location allocated or not?
They don't, except when binding a temporary to a const reference. However, newInt is not a temporary.
Ya, that's what I was thinking too.
I was just wondering if I was wrong since the topic of the site was proper reference usage.
Topic archived. No new replies allowed.