Thread: By Value and By Reference

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    85
    Zomg, a project fork lol.

    Here's a question: what's the difference between these:

    Code:
    void a(std::string x) {}
    and

    Code:
    void a(std::string& x) {}
    ?

    Or do these apply only when I have const before ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Passing by value means a copy is made. Passing by reference does not involve copying. You could read this FAQ on references.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    another thing is that the second version is able to change the string x references

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    Quote Originally Posted by pheres View Post
    another thing is that the second version is able to change the string x references
    Which means that if the purpose of using the reference is only to avoid the copying overhead and not to change the object it refers to, a const reference should be used.

Popular pages Recent additions subscribe to a feed