I know how to write reference
and pointer
.
What I want to know is
Which is more appropriate to write reference
or pointer
.
In some cases, this is specified (for example, the ++ operator only writes reference
) and is not specified
Usually, when a variable changes in the middle, everyone uses a pointer.
void add_one(int& n) { n += 1; }
void add_one(int* const n) { *n += 1; }
int main() {
int a = 0;
I don't know if add_one(a); // a changes or not. a = a+1 may be returned, but a+1 may be returned?
expected to change add_one(&a); // a
}
Rather than using a reference, you can see what you're doing right now Is it better to use a pointer than a reference to convey clearly what you're doing? Then should I use the reference only when I really need it (++ operator)?
c++ reference pointer
It is best not to use a pointer.
Using a pointer makes it difficult to read or follow the code. This code is not secure. Unexpected situations can happen later.
So the best way is to use a pointer only when you think there's no other way.
For example, if the function can return nullptr
, you must return the pointer.
In the code you asked, you do not need to write pointer
for the following reasons.
Receiving pointer
as a factor value is accepted as receiving nullptr
as a factor, and nullptr
also means that the function works well.
However, in the code you asked,
Therefore, we recommend that you write reference
.
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
914 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.