1

Complete C++ beginner here. Can someone help me understand the difference between these two approaches for passing a string into a function in C++? The second version I saw in an example online.

On the surface, both seem to work fine - what is the purpose of using the additional "const" and the "&" in this case? Does it have some implications for memory usage inside the function itself only (because the "&" means it is a reference) ?

#include <iostream>
using namespace std;

void printPhrase(string phrase_to_print){}
    cout << phrase_to_print << endl;
}

int main(){}
    std::string phrase = "This is my phrase";
    printPhrase(phrase);
    return 0;
}
#include <iostream>
using namespace std;

void printPhrase(const std::string& phrase_to_print){
    cout << phrase_to_print << endl;
}

int main(){
    std::string phrase = "This is my phrase";
    printPhrase(phrase);
    return 0;
}
teeeeee
  • 641
  • 5
  • 15
  • The 1st one implies that a copy should be created from the passed value (at least in certain circumstances), the 2nd one just passes a reference, and prevents using invalid functions of the parameter. – πάντα ῥεῖ Oct 06 '22 at 12:21
  • 2
    Does this answer your question? [Is it better in C++ to pass by value or pass by reference-to-const?](https://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-reference-to-const) Maybe a bit more than you wanted to know, but I hope it answers your question. – Lukas-T Oct 06 '22 at 12:21
  • In a nutshell: Passing a reference avoids copying the object, making it `const` ensures the original cannot be changed via the reference. – Jesper Juhl Oct 06 '22 at 12:23
  • @churill Yes that answers it nicely. Thanks for pointing it out. – teeeeee Oct 06 '22 at 14:41
  • 1
    @JesperJuhl Thanks for the succinct information, that's helpful. – teeeeee Oct 06 '22 at 14:41
  • 1
    @JesperJuhl Just to clarify - using the first method will really use double the memory allocated to the "phrase_to_print" variable? Because it exists before the function is entered, and then once inside the function another copy is made. So both are stored in memory simultaneously at some point? Do I understand it right? – teeeeee Oct 06 '22 at 14:44
  • 2
    @teeeeee That is a reasonable way to think about it. But, once the code passes through your compilers optimizer, many things may happen... – Jesper Juhl Oct 06 '22 at 14:46

0 Answers0