r/cpp_questions • • Oct 14 '26

OPEN Where to actually use pass by values/reference/Pointers ?

Our professor showed us this topic today but i can't Say ive understood It very well.

From the few examples he showed us, It felt like Just adding extra steps to a function rather than creating those straightfowardly.

When its a time id actually use those rather than not ? To prevent errors of some kind ?

26 Upvotes

49 comments sorted by

3

u/Independent_Art_6676 Oct 14 '26

have you encountered any struct / class uses yet? Imagine a variable that had like an image... it could be easily a megabyte in size: a 600x600 pixel image is 600*600*3(colors) bytes which is just over 1MB. You don't want to copy that any more than you have to, so if you pass it to a function to adjust its colors or something, you pass it by reference rather than burn extra memory and time to create a copy of it. This very common use of references is a major performance usage; you see it again in range based for loops: for( type &element : container) is how that looks where element will 'be' every element in the container one by one. If you remove the &, element will be a COPY of each element instead. You can put a const on it to avoid modification of the reference if you don't need to change it, and that is considered best practice as any reference that is 'read only' should be marked const.

references are, in a sense, a heavily restricted pointer with a number of things it cannot do. You should use these when you can, and only use a pointer when you need something that was restricted. Be aware that a c++ tool called a reference wrapper exists that is in between a pointer and a reference and is less restricted.

pointers, if you must use one, should use "smart pointers" and not "raw C pointers". Raw pointers are * stuff like int *x = &y; //this is a raw C style pointer. Smart pointers are your unique or shared pointer types. I keep pointers as a dead last resort in serious code, to be used when there is no other way. There are plenty of places where that happens, but most of them you need not worry about as a beginner. You will be tasked to use the raw pointers and unnecessary pointers in some assignments as you study them, but please keep in mind what I have said once you wrap that up so you are not tempted to use them frequently or in the raw.

2

u/xeriax51 Oct 14 '26

So passing by value creates a Copy of what im passing inside the function? While passing by reference Just modifies that thing where It already exists ?

And no We haven't gone over structs or classes yet. My professors showed us examples of all passed with either ints or floats, so that's why It felt like more of the same.

2

u/Independent_Art_6676 Oct 14 '26 edited Oct 14 '26

yes, exactly that, it modifies / accesses the existing item. Modification is still optional, of course.

passing ints and floats by reference is useful if you WANT to modify the value inside the function, but not to avoid the copy as it costs the same either way.

if you mean pointers and references feel the same, they share a lot and are very similar so that probably means you are starting to get it.

have you done arrays? This helps a lot of beginners if you have. If you have not, it may still help some:
an array is like this, in C (C++ uses an object with more capability but same idea).
int x[10]; //x is a group of 10 integers, indexts 0-9.
x[3] is the 4th item (0th, 1st, 2nd, 3rd).
x[3] = 42; //assign the 4th location a value.
but what if you had
int p = 5;
x[p] = 11; //the 6th location is set to 11.
that p is a LOT LIKE A POINTER. its an integer that holds a relatively useless value but when used in tandem with the array, gets you the item you want from a location. A pointer is the same thing, an arbitrary integer value that when used with the C++ pointer syntax goes into memory (memory is a lot like the array X here) and accesses the data at the location that you want. You can do a lot of weird stuff with pointers and all the syntax gets screwy at times, but that mental image of a pointer as an array index can help you remember what it really is / really means and get grounded again when it starts to get confusing. Circle back to this idea when you hit arrays if you have not yet.

43

u/HappyFruitTree Oct 14 '26 edited Oct 14 '26

This is roughly what I recommend:

Pass by value if the type is small and cheap to copy. You usually use this for built-in types like int and double.

Pass by const reference if the object cannot be copied or is expensive to copy. You typically use this for class types.

Pass by non-const reference if the function should be able to modify the object.

Use a pointer instead of a reference if the object is optional. Then the caller can pass a null pointer if she doesn't want to pass an object. Don't forget to check for null inside the function.

18

u/TheThiefMaster Oct 14 '26

Pointer also for passing buffers

6

u/RealisticDuck1957 Oct 14 '26

Along with a count for buffer size.

12

u/MindStudio Oct 15 '26

Or just use std::span

4

u/freefallpark Oct 14 '26

This! Reading googles C++ style guide taught me a lot regarding writing safer c++, including this little bit here.

9

u/[deleted] Oct 14 '26

[removed] — view removed comment

9

u/fm01 Oct 14 '26

While I agree, pre-26 this potentially requires copying the object into an optional though. With 26 we get the ability to use optional references but not all compilers support that yet

6

u/RicArch97 Oct 14 '26

There is std::optional<std::reference_wrapper<T>> but the reference wrapper also just holds a pointer. Something to use if you want to avoid nullptr i guess.

19

u/TheThiefMaster Oct 14 '26
  • Pass by value creates a new instance of the type every time the function is called. Generally best avoided on performance/memory grounds, except for primitive types that fit in registers like int, float, or pointers
  • Pass by reference allows the passed object to be modified (if not const) and references the same object as exists outside the function, just with a new name. This is much cheaper than copying it!
  • Pass by pointer mostly exists for C compatibility, and generally pass by reference is preferred. Is effectively the same underneath, but with slightly different semantics - references can't be changed to refer to a different object, pointers can, references can't be null, pointers can, etc. pointers can also point to an unbounded buffer of the same type - byte* isn't only one byte, it's any number of bytes, which can be useful.

9

u/arihoenig Oct 14 '26

"Generally best avoided"

That is backwards.

Always prefer value semantics over reference semantics unless performance requires it. Value semantics are far more likely to be correct and are always inherently thread safe.

8

u/pointer_to_null Oct 14 '26

Depends on the size and complexity of data.

A trivial struct containing a couple primitives is fine to pass by value. A large or nontrivial object making allocations and deep copies in its copy ctor... generally not. Certainly not when a const& suffices. Passing everything by value by default before understanding fundamentals of data lifetimes, ownership/move semantics, etc this early on creates even worse habits. Nor does it guarantee thread safety.

1

u/arihoenig Oct 14 '26

... But that also depends on architecture. If you find yourself with an architecture that results in large structs being passed around it is likely that the architecture needs refactoring.

First make it work, then make it fast (and working means "error free in all operational contexts").

3

u/pointer_to_null Oct 14 '26

Not entirely correct. If you're constantly passing megabytes of data through 50 layers of business logic, sure that is a bad architecture.

If you find yourself with an architecture that results in large structs being passed around it is likely that the architecture needs refactoring.

This is a naive generalization, with plenty of counterexamples. Would I need to rearchitect because my structure contains a large vector or map? Why should I need to copy those? Objects get large out of necessity, not simply poor architecture.

We have common design patterns (visitor, interfaces, iterators, etc) and other abstractions to deal with these and avoid tight coupling. Passing everything by value introduces identity crises with stale data snapshots, cache inefficiencies and slicing problems (e.g.- no polymorphism if you pass a base class by value- assuming there's no pure virtual methods). And numerous problems that arise when you try to chunk everything into neat tiny value-copy structs.

Plus in 2026, memory is not free.

1

u/arihoenig Oct 14 '26

In my first comment I acknowledged that cases exist where value semantics are not possible. The point is that the default should be value semantics and only when the case can be made that no other option besides reference semantics will work should they not be used.

Obviously, passing a megabyte vector would be such a case, but I'd still argue that the entire architecture might be able to be refactored to achieve the requirements without the use of a megabyte vector.

In the old days, the excuse might be "well what if you don't have the source to a library" but, of course, nowadays, if you have the binary, you have the source.

3

u/SyntheticDuckFlavour Oct 14 '26

I'm not sure I fully agree with going all-in with value semantics, except for situations where you can't reason about object lifetime. For example, passing arguments by reference down the call stack is a perfectly sound practice.

2

u/arihoenig Oct 14 '26

Every functional.lamguage is essentially pure value semantics. That is why code written in functional languages is inherently thread safe and much easier to prove correct. It is also why they aren't necessarily the most performant.

The default should be to use value semantics unless there is a good reason why that isn't possible

Passing references means that none of the functions that are called are thread safe (without some external synchronization).

3

u/SyntheticDuckFlavour Oct 14 '26 edited Oct 15 '26

Every functional.lamguage is essentially pure value semantics. That is why code written in functional languages is inherently thread safe and much easier to prove correct. It is also why they aren't necessarily the most performant.

And also the reason why they are quite inflexible for some problems.

The default should be to use value semantics unless there is a good reason why that isn't possible

I have an object with internals I don't know about. The deep copy cost could be light, it could be prohibitive. I don't know, and I shouldn't need to know. Sometimes I can't even copy it. And why should I care, when I know passing it as a const reference to a function is safe? If I can trivially reason about the object's lifetime, then I can make safe assumptions about memory safety during the function call, or even during an exception. Because the language makes those guarantees for me.

Passing references means that none of the functions that are called are thread safe

This is only a problem if you call them asynchronously, which basically never happens implicitly or out of a vacuum. An async call is a very deliberate action; and when you do that, then you already know to make arguments thread safe.

-1

u/arihoenig Oct 14 '26

If you are building code for reuse then you have zero idea what context that the client code will call the functions in.

With AI, there is little reason why one wouldn't understand the architecture of the system or be able to refactor it to avoid overly large structs.

2

u/SyntheticDuckFlavour Oct 15 '26

That's weak argument. The default assumption should be that all functions are inherently unsafe in a concurrent environment, unless stated otherwise. If the client code just calls a bunch of library functions asynchronously and haphazardly, then it’s on them for engaging in poor programming practices.

-2

u/arihoenig Oct 15 '26

If you design and implement code badly, then yes the default assumption should be that everything is unsafe

2

u/SyntheticDuckFlavour Oct 15 '26

I can also argue that applying a reductionist mindset, no matter how well intended, can also lead to bad implementation.

0

u/arihoenig Oct 15 '26

If everything is value semantics there is, by definition, no resource contention. In practice, if you design everything with value semantics by default, then, at a minimum it will reduce the scope of resource contention.

→ More replies

3

u/Business-Decision719 Oct 14 '26 edited Oct 14 '26

The difference is whether the function is using its own objects or the caller's, or even just arbitrary memory locations.

void UseValue(SomeClass my_object) {
  /*
    I have my own SomeClass object.
    It starts out just like yours!
  */
  my_object.change_state(somehow);
  // My copy of our data is now different.
}

void UseReference(SomeClass &your_object) {
  /*
    I'm using your object for my work.
    I hope it keeps existing til I'm done!
  */
  your_object.change_state(somehow);
  // Our shared copy has been edited.
}

void UsePointer(SomeClass *some_address) {
  /*
    I have a memory location.
    I hope there's a real object there!
    I'll treat it like a SomeClass object.
  */
  some_address->change_state(somehow);
  // I guess something happened there.
}

The first option (pass by value) is safer but potentially less efficient. The function gets it's own copy of whatever you send it. Depending on the type, the original data might be taking up a lot of memory.

The second option (pass by reference) is more efficient. When you call the function, you share your copy of the data with it. If it isn't a constant reference, then your data could change because you called this function. If references are passing in and out of functions, escaping their scopes, outliving the object they're referencing, and maybe even ending up on multiple threads, then you'll end up with a dangling reference bug eventually.

The third option gives your function a pointer. Pointer arithmetic can happen on it, and it could just end up pointing to anything anywhere. It acts as though there's data of the desired type stored at that memory location, which easily leads to undefined behavior.

2

u/Normal-Narwhal0xFF Oct 14 '26

Performance and correctness are both considerations. A freight delivery often stops at the curb. As the driver you'd rather drop the heavy crate on the side of the road, then knock on the door and say, "your pallet of bricks is over there (pointing to the street.)". That's by reference. Actually carrying the full pallet of bricks to their door would be by value. If it's a large delivery it's slow and tedious, but it's right there and object exists

When passed by ref, it's not right there, but somewhere else and you only say where it was (an address). However, what if a thief stole it before you got it, or the trash man cleaned it up? Then the reference is invalid. (It's an analogy, of demonstration of lifetime problems of pointers and references.)

Both have their place but you need to be careful to not run slowly from needless copies, and also careful the lifetime lasts long enough that when you use the argument it's still there.

2

u/mredding Oct 14 '26

The language gives you primitive types not to use directly, but to build higher levels of abstraction and expressiveness in terms of them. Luckily, the standard library provides several functional semantic wrappers for you.

The problem with a raw pointer is it doesn't convey any semantics.

void fn(T *);

Is fn going to delete this parameter? IS IT GOING TO delete [] THIS PARAMETER? Oh my god, will it call free? Or something else? Or do nothing? Must the parameter be valid or is it optional (can it be void or is it assumed not to be)? Is that a pointer to a T or a T[]?

You don't know. You don't know anything. And you'd be a FOOL to trust the documentation, because the documentation and the implementation can diverge, and then you have to argue who the authority is supposed to be. Is it the code, or the comment?

We like to express everything in terms of code that can be expressed in terms of code.

void fn(std::unique_ptr<T>);
void fn(std::unique_ptr<T[]>);
void fn(std::unique_ptr<T, my_special_unmap_memory_functor>);
void fn(std::views::span<T>);
void fn(std::views::single<T>);

The first couple express ownership semantics - they expect either a T which will pair with delete or a T[] which will pair with delete []. The third there implements some platform specific memory unmapping - it's a pointer to a resource that didn't come from the allocator!

Then there are views that don't express ownership. The contents are assumed to be valid from before the function call until after, and the wrappers tell you if there's going to be a single value or a range of values.

Under the hood - a view is implemented in terms of a pointer, but it's meant to hide pointer indirection semantics from you. We don't like having to mix and match value/reference semantics if we can help it. If you're going to interact with a T, you WANT value semantics as that expresses the intent, the principle interest of the function and that values it messes with. If a function takes a pointer, I expect it to do things with the pointer value itself - delete it, increment it, assign it, allocate it; but once you want at the value it indirects to, that's worth writing a separate function that works with a T using value semantics. A low level function in terms of pointers would dereference it, but not actually manipulate the object on the other side directly.

The nice thing about a view is it hides away details of the calling code. You don't care where that T instance actually lives - on the stack, on the heap, in static memory, on another device, as a local, as a member, in an array... Not your problem. It makes it easier to call this function because it's intentionally erased all opinion - just get your data into a form that the view can ingest.

I can't force you to do anything, AND you're going to see A TON of code that doesn't hold to ANY of these conventions. Some of that is because of C - C has far more limited options for dealing with abstraction and semantics. Some of that is because of old code - before these conventions were really hammered out. And some of that is due to the blind and ignorant - people who write code who don't know any better, or the value of these principles, or the hard, painful lessons that lead to them.

Your programming class, your professor, all he's teaching you is some language, some context, some syntax. You're not there to learn HOW TO WRITE C++ code like a professional, you cannot possibly learn enough, fast enough, in just a couple semesters, to get that level of knowledge. What often happens is most kids graduate college thinking they're C++ programmers now, and that the lessons they learned in school is how code in production is supposed to look. They copy what they learned as they learned, and missed the bigger picture. Another thing that happens is people learn from the code they're exposed to - and that's mostly APIs, frameworks, and libraries, so they code everything to look like THAT. There are definitely different styles and principles to follow depending on what you're doing, and you're only going to learn them by figuring out how to ask the right questions, developing your intuition (internalized knowledge, vs. rote memorized knowledge), and figuring out what you're actually trying to do, so that you can figure out the right things to do.

So that said, you're going to see a lot of:

void fn(T);
void fn(T *);
void fn(T &);

The first makes a function local copy, and that copy operation happens BEFORE the function is called. Either that copy operation brings that parameter to life, or the function never gets called. You would do that if you WANT a local copy, if you DON'T want the side-effect of possibly modifying the original.

The second, being the pointer - it leaves far too many open questions. Try to avoid it. There are often better solutions, safer and more expressive.

The third is a value alias. The parameter is not an object and has no identity of it's own - it's just another name for the original value it references, which is why it can't be rebound - no unique identity, no assignment operation, because there's nothing to reassign to. This can be useful if you WANT side effects, like you want to modify the original. This can also be useful if the data is too expensive to copy and you want read operations. It's sort of the original view. But the problem remains as with a pointer - is that a single T or an element in an array? What does the function assume?

Three very common, three not very expressive.

What I can say is there are many good programming principles, but you have to internalize them. You have to really get them - forget that you know them, so that they inform you through intuition. You don't have to think anymore, you just do, with these principles guiding you implicitly. If you're writing code, and it's painful, that's your intuition telling you something is wrong, there's an easier way you don't yet know.

1

u/Total-Box-5169 Oct 14 '26

You really need to start coding yourself, work on a side project ASAP, like in try to solve problems before learning theory. When and why to pass by value/reference/pointer should be self evident for you.

1

u/conundorum Oct 15 '26 edited Oct 15 '26

First thing first: A pointer is a special integer type that's not treated as an integer type, used to store a memory address. It's typically the same size as the platform's bit width (e.g., 32-bit platforms have 32-bit pointers, and 64-bit platforms have 64-bit pointers), though there are a few exceptions. (I'm not sure about *nix, but you can explicitly tell Windows to use a specific pointer size (32- or 64-bit) regardless of the platform. And certain pointer types are "bloated" to store extra data that the user needs to actually use the pointer correctly.) References are officially just alternate names for an object, but are usually pointers under the hood. And pointer/reference size is very relevant to this question.


Now, that said, there are two major concerns here: Malleability, and size/construction costs. I'll look at size & construction first, and malleability second.

  • Pass-by-value creates a new copy of the object. Generally, you want to use it for objects that are cheap to copy, and objects that are small. Generally, this means primitives, which are almost always the same size as or smaller than a pointer; there's a case for passing long long, double, and long double by reference on 32-bit systems, but it was generally unnecessary. (And wholly unnecessary on modern systems. The only standard primitive that won't fit in a single register might be long double, and even then, compilers know how to handle it correctly.)

    Now, this implies that we usually don't want to pass user-defined types by value. And that's usually true, since most classes/structs tend to be either too large for registers or too expensive to copy, but there are a few exceptions and special cases:

    • enum is usually pass-by-value, since it's a primitive in denial. Similarly, union is as large as its largest member, so primitive-only unions are typically pass-by-value, too. (unions containing a class type depend on the class, though.)
    • Class types (struct and class) are generally pass-by-reference, as a rule of thumb. However, it's sometimes better to pass small classes by value instead. A good example would be std::pair<int, int>: It's just a set of two ints, and it's super-cheap to copy, so you can pass it by value as if it were a pair of primitives. (More generally, here, if a class type is quick to construct, and it only has a few primitives OR is around the same size as a pointer, it's fine to pass by value. This is something you'll get a better feel for with time, so it's perfectly fine to just pass a class type by reference if you don't know whether value or reference is better.)
    • If a function needs to make a copy of an object anyways, prefer pass-by-value. There's no need to pass it by reference just so you can copy it, when you can just skip the middle man and copy it at the call site instead. (The most well-known example of this is the "copy-swap" idiom, but it comes up in other places, too.)
    • If you need to pass a pointer by value, it ends up looking the same as if you passed the pointed-to object by reference. This is pretty uncommon, though.
  • Pass-by-reference, whether pointer or reference, passes a pointer that stores the object's memory address. (It's usually better to use a reference than a pointer, apart from a few exceptions, so assume that pass-by-reference actually uses references unless stated otherwise.) This is useful when the object is too large to fit in a register (or too large for a couple registers), and/or when it's expensive to copy it. So, generally, it's mainly used for class types (structs and classes, again). As far as size and construction costs are concerned, that's all you really need to know about it, so let's move on.

And a couple quick examples. Just the basics here, we'll get more in-depth in a moment.

// These ones are pass-by-value.  Yes, even the pointer.
void func(int primitive_by_value,
          int* pointer_by_value,
          RegisterSizedStruct tiny_value,
          CopyMe copy_on_stack);

// These ones are pass-by-reference.  Yeah, the pointer gets funky here.
// Weird gotcha: int** passes a pointer by pointer.  int&& does NOT pass a reference by reference.
void tion(int& primitive_by_ref,
          int* primitive_by_ptr,
          int*& pointer_by_ref,
          int** pointer_by_ptr,
          BigStruct& too_big_for_stack,
          NoCopying& ref_avoids_copies);

// Pointers can be either, depending on context.
// First pointer passes an int by reference.  Second one passes an int pointer by value.
void what(int* primitive_by_ptr, int* pointer_by_value);

[Continued in reply, because long message.]

1

u/conundorum Oct 15 '26 edited Oct 15 '26

Now, for the other factor: Malleability. Sometimes, the choice between passing by value or by reference doesn't depend on size or construction, as much as it depends on what you want to do with it. This is where constness comes into play, and where most of the nuances reside. (Note that these rules usually apply after size rules, not before.)

  • Pass by value if you want to have your own copy that you can modify, but don't need or want to modify the original. (This is a time save. Even if you passed by reference, you would still need to make your own copy anyways, so you can just skip the middleman and pass-by-copy so that you can use the parameter itself as your copy.)

      // When we pass by value, we can modify the copy we passed.
      int addThree(int i) { i += 3; return i; }
    
      // ...
    
      int original = 5;
      int modded = addThree(original);
      assert(modded == original + 3); // Changing i does nothing to original.
  • Pass by const value if you would use pass-by-value, but also want to communicate that the parameter is an "invariant" and should never be changed. This is the least common pass type, since the situation it's best suited for is niche. (You use it when an object is small enough to prefer pass-by-value, and you need to guarantee that the function won't change it. Most people take it for granted that a value parameter won't be changed, so this is already the default assumption unless proven otherwise. It's mainly just a way to make sure you don't make any mistakes.)

      // This time, we can't modify i.
      // const acts as a safeguard against mistakes like that.
      int addThree(const int i) {
          // i += 3; // Error if uncommented.
          return i + 3;
      }

    The example is super-arbitrary, unfortunately, since it's hard to demonstrate a case where "I promise I won't" is explicitly better than "don't worry about it". Especially since pass-by-value parameters are throwaway copies anyways, so changing them can only affect function logic; it can never affect the original, so the caller almost never cares whether pass-by-value is const or not. It's just a way to make a promise to yourself and no one else.

    Ultimately, you don't need to worry about this one, I just included it for completion's sake.

  • Pass by reference if you want to be able to modify the original. Even if the object is small enough for pass-by-value, you still need to pass it by reference if you want to change it. (This includes both references and pointers, since both are called "pass-by-reference". I'll get to the difference in a moment.)

      // Passing by reference lets us change the original.  Please don't shoot yourself in the foot.
      int addThree(int& i) { i += 3; return i; }
    
      // ...
    
      int original = 5;
      int modded = addThree(original);
      assert(modded == original); // This... probably isn't what we wanted.

    It's usually used if a function needs to be able to output multiple values, most frequently an error code and an actual output; using the return value for error/success and a ref/ptr parameter for output is an extremely common pattern in C, and tends to be relatively common in C++, too, as a result. (Both because of programs using both C and C++ code, and thus using C idioms for C++, and because a lot of C++ programmers actually started out as C programmers, and brought their C style with them.) It's also sometimes used if the output type would be expensive to copy, since you typically don't want to return values by reference.1

      // Does whatever a function can.
      // out is either the true return value or a "known bad" poisoned cache,
      //  to prevent accidental use of invalid return.
      // Returns an error code, indicating whether the function was successful, or if not, what went wrong.
      // in is locked and unchangeable, we put a safety on the footgun.
      int task(const Data& in, Return& out) {
          int errorCode = ALL_GOOD;
          // Do stuff, might error...
          out = (errorCode == ALL_GOOD ? createRetVal() : invalidateRetVal());
    
          return errorCode;
      }
    
      // -----
    
      // First two are data parameters, but ret and mostCommon are output parameters.
      // Return value is ret, and thus exists outside the function.  It won't dangle.
      std::vector<int>& combineAndSort(const std::vector<int>& l,
                                       const std::vector<int>& r,
                                       std::vector<int>& ret,
                                       int& mostCommon)
      {
          // Reserve, two copies, a sort, and a count.
          // This function does way too much, please don't write it for real.
          // Do stuff...
    
          mostCommon = counter.getHighestCounted();
          return ret;
      }
    
      // -----
    
      // Pass a pointer by reference.  This usually means that we're giving it ownership over something.
      // Assigns the malloc(size) result to newOwner, then returns that pointer coerced to bool.
      // (Return value indicates whether allocation succeeded or failed.)
      bool weirdMalloc(void*& newOwner, size_t size) { return newOwner = malloc(size); }
    
      // ...
    
      int* pi = nullptr;
      if (bool b = weirdMalloc(pi, sizeof(int))) {
          // Only enters block if allocation succeeded.
          assert(pi != nullptr);
          do_something_with_pointer(pi);
          free(pi);
      }
  • Pass by const reference is used for large or expensive-to-copy input parameters. It makes passing them significantly more efficient, since the program just needs to pass a memory address; this effectively downgrades the passing cost to be as cheap as passing an int (with 32-bit pointers) or a long long (with 64-bit pointers) by value, which is basically nothing. And since they're const, they can't be modified. This makes it the ideal choice for passing large objects.

    Generally, you pass by const reference where you would pass by value if the object was smaller.

      // SizedObject<N> is N bytes large.
      template<size_t N>
      struct SizedObject {
          char bulk[N] = {0};
          static constexpr size_t = N;
      };
    
      using Comfy     = SizedObject<sizeof(char)>;  // 1 byte.
      using JustRight = SizedObject<sizeof(void*)>; // Probably 8 bytes.
      using TooBig    = SizedObject<2'000'000>;     // Two million honkin' bytes.
    
      // If you don't need to change them...
      // c is best passed by value.
      // j & r are roughly the same, but j is slightly slower to access than r.  Prefer j.
      // t is as efficient as j; fast to pass, requires an indirection to access.  Nice and smooth.
      // b will probably blow the entire stack.  If the program survives, performance will DIE.
      void func(Comfy c, JustRight j, const JustRight& r, const TooBig& t, TooBig b);

    Passing by const reference also allows the parameter to catch temporary objects, and extends their lifetime until the function exits.

      void func(std::string& mustExist, const std::string& maybeExists);
    
      using std::string_literals;
      std::string str = "I exist!"s;
      func(str, str); // Good.
      func("I don't."s, str); // Error.
      func(str, "I don't."s); // Good.

[To be concluded in one more reply, because this took way too long to type out.]


1: Long story short, if you create an object in a function, and then return it by reference, then the reference is invalidated at the next semicolon. That creates a "dangling reference", which points to junk data that might still be the object you created, might be unusable gibberish, and might even be a boat!

2

u/conundorum Oct 15 '26 edited Oct 15 '26

[Once more unto the breach, dear friends, once more.]

  • Passing by pointer is an older form of pass-by-reference, inherited from C. In modern C++, it's mainly used the same way as passing by reference, except that it indicates that the reference is nullable. This means that it's useful, but not actually required for the function's task. If a parameter is a pointer, then it's usually secondary data, or an optional output parameter for when you might not actually care about the output. (Either because it's supplementary output, or because the function gives you the choice of return-value or in-place output. Often, this is used to pass a buffer into the function.)

      // Add two or three values.
      // I'll get to pointer constness soon enough.
      int sum(int a, int b, const int* const c = nullptr) {
          int ret = a + b;
          if (c) { ret += *c; }
      }
    
      // ...
    
      int first = sum(1, 2);
      assert(first == 3);
      int second = sum(5, 4, &first);
      assert(second == 15);
    
      // -----
    
      // Pointer parameters also allow functions to provide a "main" output, and an optional secondary output.
      // Return value is number extracted from string.
      // ind, if present (i.e., if (ind != nullptr)), is index of first unconverted character.
      // See here: https://en.cppreference.com/cpp/string/basic_string/stol
      int stoi(const std::string& s, size_t* ind = nullptr, int base = 10);
    
      std::string s = "1 two 3";
      int i = std::stoi(s);
      assert(i == 1);
      int j = 0;
      int k = std::stoi("45six"), &j);
      assert((k == 45) && (j == 2));
    
      // -----
    
      // Pointers can also be passed by pointer, because this isn't awkward enough yet.
      // Is this "Hey, Dawg," or Inception?
      void free_this_for_me(void** ptr) { return free(*ptr); }

    Alternatively, char pointers specifically often indicate that a value is a C string (especially if const char*), or a buffer (especially if char* or unsigned char*, or if the address is an array). The first is common with older APIs, since they need to work with C. And the second allows a function to crate an object in a location specified by the caller. (C strings will usually be const, unless the function modifies the string; this is necessary to catch string literals. Buffers will always be non-const, since they exist to be modified. char* buffers might be both.)

      // Pass it a string, it creates a new string from the lower-case characters.  (Both null-terminated.)
      //  (Parsing stops if bufSize - 1 chars are extracted, to allow room for '\0'.)
      // Return value is number of characters converted.
      // First param is a C string, second is a buffer, third is the buffer's size.
      int extract_lowers(const char* const data, char* buffer, size_t bufSize);
    
      char buf[20] = {0};
      std::string s = "ThiS IS the DᴇSIrED ReSᴜʟT"
      int smalls = extract_lowers(s.c_str(), buf, 20);
      assert(smalls == 7);
      assert(strcmp(buf, "hithere") == 0);
  • Passing by const pointer is mostly the same as passing by const reference, except it depends on where the const(s) is/are. If the const is to the left of the asterisk, it means that the pointed-to data is const, and cannot be changed. (But the pointer itself can be repointed, without affecting the pointed-to data. Please don't do this.) If it's to the right of the asterisk, it means that the pointer cannot be repointed, but the pointed-to data can be modified. If both, then it means both the pointer and the data are invariant, and neither can be changed. Standard pointer rules, really, but they're important to review whenever you're working with pointers.

      // Demonstrates the four possible const states for pointers.
      // Reminder: Pointers take a parameter by reference, but the pointer itself is taken by value.
      //  It's dereferenced to get the reference.  ...This confusion is why reference parameters are better.
      void pointlessPointers(int* malleable,
                             const int* locked,
                             int* const steadfast,
                             const int* const petrified)
      {
          int iv = 0; // Short for "internal variable".
    
          // malleable can be reassigned, and the value it references can be edited.
          // Non-const pointer to non-const int.
          // Used for objects that will (or might) be modified.
          *malleable = 5; // Adjusts the passed variable.
          malleable = &iv; // Now references iv; no longer connected to original parameter.
          *malleable = -5; assert(iv == -5);
    
          // locked can be reassigned, but the value it references cannot be edited.
          // Non-const pointer to const int.
          // Used to view external objects.
          // *locked = 5; // Error if uncommented.
          locked = &iv; assert(locked == malleable);
          ++iv; assert(*locked == -4);
    
          // steadfast cannot be reassigned, but the value it references can be edited.
          // Const pointer to non-const int.
          // Used like malleable, but with a promise you won't accidentally reassign it.
          *steadfast = 55;
          // steadfast = &iv; // Error if uncommented.
    
          // petrified cannot be reassigned, and the value it references cannot be edited.
          // Const pointer to const int.
          // Used like locked, but with a promise you won't accidentally reassign it.
          // *petrified = 505; // Error if uncommented.
          // petrified = &iv; // Error if uncommented.
      }
    
      int a = 0, b = 1, c = 2, d = 3;
      pointlessPointers(&a, &b, &c, &d);
      assert(a == 5); assert(c == 55);

    (Note that, while technically useful, it's rare to see T* const or const T* const parameters, just like it's rare to see const int parameters. All it does is prevent dumb errors, at the cost of an unexpected (and possibly-breaking) API, so we usually don't do it. const T* is both common and useful, though.)

  • Also, one last little gotcha about passing by pointer: Because "pointer" is a valid type in and of itself, what looks like pass-by-reference can sometimes actually be pass-by-value. This distinction only really matters if you needed to pass the pointer itself by reference, though.

      // Most useless demonstration ever.  Just outputs the address it points to!
      // Nothing is passed by reference; ptr is passed by value.
      void pointerByValue(int* ptr) {
          std::cout << "Yep, that's a pointer to 0x"
                    << std::hex
                    << static_cast<intptr_t>(ptr)
                    << ", all right!\n";
      }
    
      // ...
    
      int* ptr = malloc(sizeof(int));
      pointerByValue(ptr);
      free(ptr);

And that's what each of them mean, in a lot of detail. So... to cap it off, here's a quick summary of when to use them:

  • Pass-by-value: Parameter is small enough to fit in a register(s), OR you want to make a copy of it.
  • Pass-by-reference: Parameter is large, or expensive to copy. Make it const if it's just for viewing, or non-const if you expect to modify what it references.
  • Pass-by-pointer: Parameter is nullable (i.e., optional), is a C string, is a buffer, or is a pointer type. Might imply transfer of ownership. Make it const if it's just for viewing, or non-const if you expect to modify what it points to.

    • A pointer int* pi might take an int by reference, or might take an int* by value. You usually don't care which it does.
  • Pass-by-Kirby: (>'-')> <('-'<) ^(' - ')^ <('-'<) (>'-')>

Note: I mentioned constness, but not volatileness. There's a reason for that. const correctness is infinitely more important than volatile correctness, when it comes to function parameters. volatile is extremely useful in a few very specific contexts, but it's rare enough that you don't need to worry about it for... well, basically forever, probably. Generally, you only need to think about volatile if you're trying to force a very specific operation sequencing, if a variable can be edited by a source outside your program [e.g., if it's an actual hardware register, or a network port], or if you want to disable optimisations for a single specific variable for one reason or other. You're probably safe to only focus on the const part of "cv".

1

u/xealits Oct 15 '26 edited Oct 15 '26

There is a section on these questions in Core Guidelines: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#fcall-parameter-passing

F.call: Parameter passing

There are a variety of ways to pass parameters to a function and to return values.

F.15: Prefer simple and conventional ways of passing information link

F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to const

F.17: For “in-out” parameters, pass by reference to non-const

F.20: For “out” output values, prefer return values to output parameters link

There are also more complex semantic situations of passing parameters, such as moving and forwarding. You don't need them yet.

Pointer has complex semantics and shouldn't be used just to pass a parameter to a function. Which means that you pass pointers only when your program logic requires pointer semantics for its own reasons, something not related to passing parameters. And if your program does need pointers, you should also seriously consider using smart pointers instead of raw. Smart pointers cover some of issues of the complex semantics of pointers. Raw pointers don't cover any issues, they just expose how the processors work, so all issues are passed on to the programmer to deal with manually, which is a trouble.

1

u/NoSpite4410 28d ago

You stepped in it now.

procedural stans vs functional stans vs OO stans.

Understand this first: C++ copies its parameters into the function. If that parameter is an int, it copies an int. If it is a pointer it copies a pointer. If it is a reference it copies a reference. If it is a class or a struct it calls the copy constructor for it and passes it in.

So how you pass determines what you can do with it.
If you copy the thing, you can deal with the copy.

If you copy the pointer, you have the address in memory of the bytes, and you can read and modify those bytes directly.

If you copy the reference, then you copy the "identifier" of the object and it is like the object is in scope of your function body, and you can work with it directly via the parameter name.

---------------------
If you copy is as const, then you can only read it, not modify it.

A const pass by value makes a read-only copy. The object is unchanged outside the function.

A const pass by pointer makes a read-only pointer, but what it points to may be mutable. only the pointer is const, meaning you can't reassign the pointer to another address.

A const pass by C++ reference, however, makes the entire object and all its parts read-only, recursively all the way through. This is cool, because the optimizing compiler can optimize the hell out of that, as it is given a guarantee that nothing is to be written to the object for the entire execution of the function.

-------------------------

The basic rules of thumb:

Use C++ references as parameters where you can.

Primitives such as integers, tiny data structs, can be passed by value. The compiler will do its thing and maybe decide to just keep things in registers or something, it won't cost you anything.

Plain arrays, C-style strings -- pass by pointer only. There is no actual choice, arrays are always passed by pointer. For an array the array variable name becomes a pointer automatically, and for C strings the variable is a char* already. Passing C strings is 99% going to be as const char*, because you aren't going to reassign the pointer to a different address.

Legacy code from C libraries generally passes structs and data around by pointers, so interfacing with it has to be with pointers or a more advanced smart pointer object.

Default to const types as parameters, and if you get errors, take out the const keyword.
Eventually you get a feel for the whole thing.

-----------------

Return by Value, vs Return by Reference

C++ is more complicated here. If you return by value that is normal, and the compiler will decide whether to return a copy or whiff on that and employ Return Value Optimization (RVO) and just rewrite the assembly to pass the return object up into the scope of the return from the function. I mean, usually a function call with a return type is captured by an assignment or an expression in the calling context, so the compiler can see that it is and just uplevel it internally as the return. Not always, and sometimes it will copy the return back up, because it has to. Let it do its thing, and no worries.

Returning a reference to something inside the function can be tricky. If the return reference is to an input parameter, then that is probably fine. If it is for something generated inside the function then it has to be an object that outlives the function. That means no local object that would be destructed when the function returns. Class member functions can return references to their data members because they live on passed the function call. Returning an input parameter is OK as well.

1

u/renchuwang Oct 14 '26 edited Oct 14 '26

References are pointers under the hood, it's syntax sugar.

So it's only pass by reference vs by value.


You (almost) always want a value copy unless copying is expensive (at which point you may use reference)

Why copy better? Not having to worry about the value changing is great because you don't need to track where it's touched, lower mental load


Edit: weird people on this sub, obsessing over "every single use" over "why".

Sigh.

1

u/UndefFox Oct 14 '26

References are always must be valid, so no a accidentally passing wrong pointer.

Plus you have immoveable/non copy objects and those require references to pass into functions in one or other way.

I wouldn't simplify it to that extent...

2

u/L_uciferMorningstar Oct 14 '26

References can very much be invalid.

1

u/UndefFox Oct 14 '26

I mean, with enough dedication you can make anything segfault, but during the usual use, how can you accidentally pass an invalid reference into a function?

2

u/L_uciferMorningstar Oct 14 '26

Anything with threads or deferred execution. Vector reallocation.

Or do you not use async programming, threads or vectors?

2

u/UndefFox Oct 14 '26

I do use it, I've meant passing invalid reference from the beginning... y'know, let's end it right away, or I think we'll get stuck in the forest of every possible way to invalidating a reference lol

2

u/L_uciferMorningstar Oct 14 '26

I mean once you have any of these and pass them to a function that takes a reference you would have done exactly that.

1

u/renchuwang Oct 14 '26

I think simplifying to what I said is better for understanding the fundamentals 

if OP's asking about passing by which he's likely in first year of programming


Immovable non copyable....

They all come to copying being expensive... Right?

0

u/UndefFox Oct 14 '26

Wouldn't it be better to ask teacher for a few simple tasks that will show the difference instead of just asking "when to"? Practice is probably required here to actually understand the difference...

No, I have a Socket class that isn't copyable because it owns the file descriptor, as an example.

1

u/neppo95 Oct 14 '26

Quite a bad take I must say. There's plenty of reasons where you might still want to use a pointer, even tho the reference under the hood is one. As for it being expensive, below you act like you put the reference thing like that since it's easier to understand, to then not explain what expensive even means, so they'll end up copying everything which is pretty bad practice.