Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

23
  • 59
    The drawback of returning by pointer: now you've got to track ownership of that object and possible free it. Also, pointer indirection may be more costly than a quick copy. There are a lot of variables here, so using pointers is not universally better. Commented Oct 19, 2017 at 14:15
  • 19
    Also, pointers these days are 64 bits on most desktop and server platforms. I've seen more than a few structs in my career that would fit in 64 bits. So, you can't always say that copying a pointer costs less than copying a struct. Commented Oct 19, 2017 at 15:01
  • 40
    This is mostly a good answer, but I disagree about the part sometimes, very rarely, this is what you want, but most of the time it's not - quite the opposite. Returning a pointer allows several kinds of unwanted side effects, and several kinds of nasty ways to get the ownership of a pointer wrong. In cases where CPU time is not that important, I prefer the copy variant, if that is an option, it is much less error prone. Commented Oct 19, 2017 at 17:28
  • 6
    It should be noted that this really only applies for external APIs. For internal functions every even marginally competent compiler of the last decades will rewrite a function that returns a large struct to take a pointer as an additional argument and construct the object directly in there. The arguments of immutable vs mutable have been done often enough, but I think we can all agree that the claim that immutable data structures are almost never what you want is not true. Commented Oct 19, 2017 at 19:19
  • 7
    You could also mention compilation fire walls as a pro for pointers. In large programs with widely shared headers incomplete types with functions prevent the necessity to re-compile every time an implementation detail changes. The better compilation behavior is actually a side effect of the encapsulation which is achieved when interface and implementation are separated. Returning (and passing, assigning) by value need the implementation information. Commented Oct 19, 2017 at 20:29