CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2007
    Location
    South Africa
    Posts
    86

    Pass-by-value vs pass-by-reference

    From a multithreaded and multi-processor/core perspective, what would be safer, pass-by-value or pass-by-reference?

    I know there's no hard and fast rules, but what would you consider as a general guideline?

    To me it feels that pass-by-reference is more risky in a multithreaded environment. Another thread can modify an object while a function is busy operating on it. Using pass-by-value decreases the chance of a mess happening. The downside of course is the overhead associated with passing large objects by value.
    Last edited by links; August 25th, 2010 at 02:58 AM.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Pass-by-value vs pass-by-reference

    The real answer is, this isn't a sufficient question. You can follow guidelines like "prefer local variables to globals" and "don't use local statics" to make multithreading easier, but at the end of the day, you need to know for certain precisely where and when an object might be modified or read by more than one thread. Guessing isn't good enough.

    However, one of those good rules of thumb you can follow is that passing by const reference is almost always as safe as passing by value, in terms of behavioral guarantees.

  3. #3
    Join Date
    Nov 2002
    Location
    California
    Posts
    4,556

    Re: Pass-by-value vs pass-by-reference

    Passing by const reference provides a behavioral guarantee only on the function to which the reference is passed. It does not provide any guarantees on the function doing the passing. If these functions are in different threads, it thus might happen that the passed-to function finds that the underlying value is changed out from underneath it.

    It might be better to prefer pass by value, since then each function has its own local copy of the value, even though those values can easily become desynchronized.

    PS: Sorry for the delayed post

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured