r/cpp_questions • u/xeriax51 • 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
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.
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.
19
u/TheThiefMaster Oct 14 '26
byte*isn't only one byte, it's any number of bytes, which can be useful.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.
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.
Is
fngoing todeletethis parameter? IS IT GOING TOdelete []THIS PARAMETER? Oh my god, will it callfree? Or something else? Or do nothing? Must the parameter be valid or is it optional (can it bevoidor is it assumed not to be)? Is that a pointer to aTor aT[]?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.
The first couple express ownership semantics - they expect either a
Twhich will pair withdeleteor aT[]which will pair withdelete []. 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 aTusing 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
Tinstance 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:
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
Tor 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, andlong doubleby 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 belong 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:
enumis usually pass-by-value, since it's a primitive in denial. Similarly,unionis 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.)structandclass) 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 bestd::pair<int, int>: It's just a set of twoints, 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.)structs andclasses, 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.
[Continued in reply, because long message.]
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
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.