Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

On pg. 149 of Jumping into C++, the author states:

In general, you should not store memory that you just allocated in a reference:

int &val = *(new int);

The reason is that a reference does not provide immediate access to the raw memory address. You can get it using & , but generally references should provide an additional name for a variable, not storage for dynamically allocated memory.

What does this mean on the right-hand side of the reference intialization?

I understand the notation of declaring (and immediately initializing) a reference as follows:

int x = 1;
int &ref = x;

But I don't understand what *(new int) refers to in the passage. And whatever it means, is it illegal to do this, or just a bad practice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
147 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, you misquoted it. It's *(new int) and it means the same as any other *<some pointer here> — it dereferences the pointer.

It's the same as this:

int* x = new int;
int& ref = *x;

with *x of course being the expression that refers to the dynamically-allocated int object. Thing is, your way you don't have a variable name x to play with and now must write delete &ref at some point, which is just kinda weird.

Avoid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...