Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does a function output parameter (a reference paramter) change before the function returns?

Basically I want to know in C++ if I call a function and pass the arguments by reference, then the arguments are modified only after the function returns or it is possible that they get changed exactly when they are modified inside the body before reaching to a return point?

I need to return some objects before deleting them at the end of a function. Obviously it is not possible to access the already deleted object when the function returns.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A reference can be seen as an alias to the actual object it’s referencing so whenever you mutate an object via a reference, it’s directly affecting the referenced object.

void foo(int& my_int) {
    my_int = 10;        // <- the change happens exactly here

    // `an_int` declared in `main` is now 10

    // do other things ...
}

int main() {
    int an_int = 0;
    foo(an_int); 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading