what even is a "reference"?

Ғылым және технология

When I was learning to program C++ as a beginner, I thought something was weird about C++ references. It's like a pointer.... but its not a pointer? In this video, we discuss how to use a reference, what a reference is, and what a reference actually does under the hood. If you're new here hit that subscribe button for new videos like this every week!
Music: Strange Stuff - Matt Harris
🏫 COURSES 🏫
Learn to code in C at lowlevel.academy
Why Are Switch Statements so HECKIN fast? • why are switch stateme...
Why Do Header Files Exist? • why do header files ev...
How Does Return Work? • do you know how "retur...
🔥🔥🔥 SOCIALS 🔥🔥🔥
Follow me on Twitch: / lowlevellearning
Low Level Merch!: www.linktr.ee/lowlevellearning
Follow me on Twitter: / lowleveltweets
Join me on Discord!: / discord

Пікірлер: 264

  • @LowLevelLearning
    @LowLevelLearning Жыл бұрын

    C++ people, I still love you ❤ BUT ONLY IF YOU FOLLOW ME ON TWITTER >:(

  • @user-mz8qj7bz8h

    @user-mz8qj7bz8h

    Жыл бұрын

    Nice video bro, could you please drop the name of the intro music :)

  • @SKBotNL

    @SKBotNL

    Жыл бұрын

    @@user-mz8qj7bz8h Sorry, that was the outro music not the intro music

  • @capitalists1526

    @capitalists1526

    Жыл бұрын

    @@sangitakumari5482 if you are a minor you shouldn't be sharing your age at random on social media

  • @SKBotNL

    @SKBotNL

    Жыл бұрын

    @@user-mz8qj7bz8h Found it! It's Strange Stuff by Matt Harris kzread.info/dash/bejne/h4Rol5mlfKXAnNY.html

  • @piotrkozbial8753

    @piotrkozbial8753

    Жыл бұрын

    You're spreading misinformation and still didn't get the flame war you wished for. C++ programmers were not "triggered", they explained your omissions politely in the comments. Instead, you seem to have triggered C programmers to hate on C++ in most stupid, irrelevant ways.

  • @williamdrum9899
    @williamdrum9899 Жыл бұрын

    Pointers References Array Indexes "Corporate wants you to find the difference between these pictures" Assembly Programmer: "They're the same picture"

  • @joey199412
    @joey199412 Жыл бұрын

    Modern compilers are really REALLY optimized. But references can in a lot of times result in more efficient compiled code because they are more limited and thus the compiler can eliminate a lot of possibilities or potential intentions . It's also easier to use for newcomers to low level languages so you usually just tell junior programmers to use references instead of pointers to save yourself from future headaches.

  • @matthew314engineering7

    @matthew314engineering7

    Жыл бұрын

    That makes sense. I was getting the safety insight but didn't see the performance one right away.

  • @ghosthunter0950

    @ghosthunter0950

    Жыл бұрын

    Really? I had a harder time with references than pointers when I first learned each.

  • @mastershooter64

    @mastershooter64

    10 ай бұрын

    "more efficient compiled code because they are more limited and thus the compiler can eliminate a lot of possibilities or potential intentions" I think it's just because passing by reference doesn't make a copy of the object so you don't spend time copying a large object + you don't waste memory making another copy of the large object. So it saves time and memory! But I'm not sure what you mean by "they are more limited and thus the compiler can eliminate a lot of possibilities" That's a reason why you don't pass fundamental types by reference because that just passes in a pointer which would usually be more memory than the fundamental data type like a char or an int

  • @sinom

    @sinom

    9 ай бұрын

    ​​@@mastershooter64 more limited than pointers. Not more limited than copies. With a pointer you could potentially do a lot of stuff, like pointer arithmetic and they can also be null. All of this needs to be allowed with pointer parameters by the compiler. References on the other hand are just that. A reference to something. No nulling, no arithmetic etc. This means the compiler can then do some theoretical optimizations where it just handles the original object directly instead of a pointer to the object. This is pretty rare though so in general references are just safer non nullable pointers

  • @teranyan
    @teranyan Жыл бұрын

    I once "failed" a job interview because the interviewer knew less about references than I did and didn't believe me that the reference is much more powerful as optimization tool than "it's always a pointer under the hood". Which is exactly what your disassembly example is wrongly showing. The reference is NOT a pointer. If you compile that program with O3, it will probably resolve to pushing "3" into a register and returning it, because the compiler understands at compile time what your code does already. Because you were correctly using references (and an easy to to optimize pointer dereference).

  • @sinom
    @sinom Жыл бұрын

    References are only very rarely used like this. Usually they are mainly uses in function signatures because it allows to pass things into a function similarly to how you could with a pointer, but without the function then having to null check the input.

  • @Bwallker
    @Bwallker Жыл бұрын

    Some nitpicks/extra info: 1. Refrences don't have to be implemented using pointers by the compiler. Most of the time they are, because that is a sensible way to implement them, but if you wanted to be edgy you could write your own compiler that implements them differenty. 2. Even though references and pointers are the same thing at runtime (in most compilers), they are considered to be two very different things by the type system, and using references can result in better codegen because the compiler can give stronger guarantees about references than it can about pointers.

  • @clehaxze

    @clehaxze

    Жыл бұрын

    And that's why some senior C++ developers use pointer and reference interchangeably. It's confused me in the beginning. But then it makes sense afterwards.

  • @TheFakeVIP

    @TheFakeVIP

    Жыл бұрын

    Thanks, I was going to ask about that, makes sense. For example, if passing a const reference to an object that can fit in a register, I imagine the compiler could choose to pass the object directly instead of passing a pointer to it.

  • @gustawbobowski1333

    @gustawbobowski1333

    Жыл бұрын

    How exactly can you implement references other than pointers?

  • @9SMTM6

    @9SMTM6

    Жыл бұрын

    @@TheFakeVIP doesn't have to be a const& I think, because of the rules for references or should be easy to check for the compiler if copying suffices. const& is more for the user to enforce that, as well as a promise for the API I'd say.

  • @9SMTM6

    @9SMTM6

    Жыл бұрын

    @@gustawbobowski1333 also seems a bit tricky to me... Like swift inout parameters are modeled in its model? Seems wasteful, but perhaps that suffices.

  • @minikindaniil99
    @minikindaniil99 Жыл бұрын

    If somebody thought that this is too sensible for c++, I've got your back: c++ also has - const reference and rvalue reference that cause lifetime extension of a temporary - universal/forwarding reference that change between rvalue and lvalue reference automatically together with CTAD - std::reference_wrapper because you can't create containers of references - ref qualified methods that enable overload resolution based on if object is temporary or not - still has many of pointer's problems, as it is easy to create dangling reference by accident

  • @free_mind

    @free_mind

    Жыл бұрын

    To be fair, the things you mentioned have their uses when used at that right place and time. Universal references for example are very useful in generic code. It can be overwhelming to a beginner to learn about the OCEAN of C++ features all at once though.

  • @mareknetzel
    @mareknetzel Жыл бұрын

    The content of your channel is exactly what I always felt missing while studying (long time ago ~1999 ) and in general online tutorials. Thanks a lot, the form is great and the simplicity of it shows your great understanding of the subject.

  • @metal571
    @metal571 Жыл бұрын

    As a full time professional modern C++ dev, I love this channel - no triggering here. I think the best way to think about references is as a *const* pointer underneath, which is not the same thing as a pointer to const (however machine code gen may be identical). That's an interesting C syntax quirk that you could also cover if you haven't already. Keep up the great work on these videos

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    YAY 🖥

  • @nishanth6403

    @nishanth6403

    Жыл бұрын

    Yes , a const reference would then be a const pointer to a const

  • @filipcimo998
    @filipcimo998 Жыл бұрын

    Reference to reference actually exists (in the point of view of syntax, not functionality), it is called rvalue reference, so it can refer to a temporary object and it is a operator used for move semantics in C++. This is a lvalue reference so as you said, it has to refer to some valid and already existing object.

  • @Coppertiel

    @Coppertiel

    Жыл бұрын

    The syntax for an rvalue reference is "foo&&", but calling it a "reference to reference" is just for fun.

  • @gustawbobowski1333

    @gustawbobowski1333

    Жыл бұрын

    What's the actual use?

  • @ronaldweasly561

    @ronaldweasly561

    Жыл бұрын

    @@gustawbobowski1333 string text = "foo"; string text2 = text; Copying "foo" to text2 (which is expensive), instead of copying just move it text2 = std::move(text) std::move using &&

  • @Spiderboydk

    @Spiderboydk

    Жыл бұрын

    Rvalue references are not references to references, despite coincidentally using the && symbol.

  • @claywynn9837

    @claywynn9837

    Жыл бұрын

    @@gustawbobowski1333 move semantics. By having an r-value reference passed to a move constructor you are signifying that it's "ok to scavenge" from this reference. An easy to understand example is moving a std::vector. Std::vector points to a heap allocated array. If you want to copy to a new vector, you must allocate a new array and copy each element of the first vector. With a move constructor you can just steal the pointer from the other vector, and tell that other vector "I have your array now, don't try to use it anymore"

  • @usr-bin-gcc3422
    @usr-bin-gcc3422 Жыл бұрын

    I think it is a bit misleading to say that a reference is a pointer. A pointer is a variable that stores the address of another variable, i.e. there is some memory allocated to store that address. A reference is establishing another syntactic label in our program for a variable that already exists, so no additional memory is required to store the address. Try taking the address of the pointer and the address of the reference. The address of the reference will be the same as the address of the variable that is being referenced, but the address of the pointer will not be the address of the variable that is being pointed to. It is up to the compiler to decide how to implement this, but they are semantically different, and it is worth understanding the semantics as well as the implementation. In your example, the compiler would be free to substitute x everywhere it sees rx and the program would be semantically the same as rx is just a new label for the same variable, in which case there would be no need for a pointer to implement it.

  • @ohwow2074
    @ohwow2074 Жыл бұрын

    References are limited pointers. They are far less flexible than pointers but this also means that they're safer. But of course things can easily go wrong with references too (like dangling references).

  • @thebestwizz
    @thebestwizz Жыл бұрын

    With a reference you are less likely to mess up with memory. The golden rule nowadays is to avoid pointers if a reference can be used. It's especially useful when you want to pass on a HUMONGOUS array onto a function, using a reference is clean and simple.

  • @jaysistar2711
    @jaysistar2711 Жыл бұрын

    You seemed to forget the biggest difference: References can be optimized away, while pointers cannot (always) be. Anytime there are constraints that must be obeyed at compile time, then the optimizer has more flexibility because it doesn't have to maintain some potentially optimizable semantics at runtime.

  • @VTdarkangel
    @VTdarkangel Жыл бұрын

    This is probably heresy for most C++ programmers, but I always preferred using pointers instead of references. The * operator was a key that reminded me that I was accessing a different bit a of memory that was potentially out of scope and to tread carefully about what I did with it. I understand some of the safety concerns that references address, but I never had those problems. Pointers were just easy for me.

  • @JurekOK

    @JurekOK

    Жыл бұрын

    this is not so much a heresy; it's more like, some people are religious about c++. This is why Linus Torvalds wrote git in C, and not C++. To avoid religious wars.

  • @v01d_r34l1ty

    @v01d_r34l1ty

    Жыл бұрын

    ​@@JurekOK i mean it's not heresy, it's just not standard practice anymore. raw pointer access in abundance is arguably why C++98 was terrible (in retrospect; i never used it). smart pointers / RAII and references make c++ not only easier to work with, but a lot easier to make memory safe in comparison to C. you still can use raw pointers, and at some times it makes sense to (i.e. same situation with goto), but it shouldn't be a standard practice.

  • @ericbwertz

    @ericbwertz

    6 ай бұрын

    @@JurekOK Not sure how that avoids a religious war -- it's a pretty potent thumb in the eye of C++.

  • @JurekOK

    @JurekOK

    6 ай бұрын

    @@ericbwertz :-) Good one!

  • @jaimeguzman4655

    @jaimeguzman4655

    5 ай бұрын

    Strictly talking about pointers vs references. Since the actual functionality of it is near identical besides syntax, it is more of a guideline thing The one thing that references offer is that they can't be null, so if need to pass null I stick to pointers

  • @CanoTheVolcano
    @CanoTheVolcano Жыл бұрын

    thank you so much for this vid, I'm a mostly self taught C++ dev, and I'm working on my first big project, and I was very confused by the &object semantics being used in function arguments in this library I'm using. All my uni professors switched to Java/JS for all instruction over a decade ago, but I've always been really fond of C++'s high performance and modular syntax

  • @ashenone5774
    @ashenone5774 Жыл бұрын

    Thank you my good sir! I was actually afraid to ask this question, and here you are already taught me something new.

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    Gotchu man!

  • @ca2121
    @ca2121 Жыл бұрын

    Wow after all this time I finally got the idea around references in C++. The assembly lines helped a lot. Thank you so much!

  • @UkranianStallion
    @UkranianStallion Жыл бұрын

    Thanks, low level programming always fascinate me, it's like opening a forbidden scroll for a high level programmer

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    Glad you enjoy it!

  • @Mnogojazyk
    @Mnogojazyk Жыл бұрын

    Thank you! I took C and C++ thirty five years ago. From what the instructors said and did not say, I figured out then that references had to pointers, but I could not get confirmation or refutation. This is this time I have gotten it - and an explanation how so and how references differ from pointers. Thank you!

  • @rohanjoshi8785
    @rohanjoshi8785 Жыл бұрын

    Great video..!! I wasn't aware that ASM for both implementation would be the same.. good to know. This reminds me one of line of Linus Torvals - "When I read C code, I know what Assembly language will look like and that's something that I care about ".

  • @mikegofton1
    @mikegofton1 Жыл бұрын

    Thanks , really relevant. I’m teaching myself C++ and this confirmed what I thought - spicy pointers 🙂

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    Glad it was helpful!

  • @gustawbobowski1333

    @gustawbobowski1333

    Жыл бұрын

    They actually are watered down, seeing as they are limited pointers... Or maybe spiecier for the programmers because more focused on their purpose and utility? Idk

  • @nishanth6403

    @nishanth6403

    Жыл бұрын

    @@gustawbobowski1333 They are watered down intentionally, to enforce stricter code and help better compiler optimization.

  • @m4rt_
    @m4rt_ Жыл бұрын

    add -ggdb as a compiler flag to gcc/g++ to get more info in the assembly when using gdb

  • @bazoo513
    @bazoo513 Жыл бұрын

    Unlike some other videos on this topic I watched recently, this one is clear and to the point.

  • @gustavopeixoto8682
    @gustavopeixoto8682 Жыл бұрын

    I can not tell you how glad I am to find out your channel. All the subjects that I like has always been here. Subscribed++ :D

  • @asdqwe4427
    @asdqwe4427 Жыл бұрын

    Seems like some powerful constructs that I can use to ultimately create more bugs

  • @cno9984
    @cno9984 Жыл бұрын

    It's all easy and fun until you get into rvalue references and move semantics.

  • @brawnie3969
    @brawnie39698 ай бұрын

    I'm so grateful for this kind of videos, you have helped me a lot.

  • @LowLevelLearning

    @LowLevelLearning

    8 ай бұрын

    Happy to help!

  • @ABaumstumpf
    @ABaumstumpf Жыл бұрын

    References are NOT pointers. They can be implemented as pointers but they are not the same (and have some very distinct behaviours and limitations). For one - a reference is not an object. There is no welldefined memory address the reference resides in. It depends on what those references are referencing - for example refrences to non-static member likely will increase the size. other things would be lifetime-extension. It is kinda like saying that "int" is a 32bit 2's comeplement integer type. Yeah - compilers MOSTLY do that, but that is not required.

  • @joiscode3832
    @joiscode3832 Жыл бұрын

    I love these vids. They have helped me understand some confusing things. Also i finaly got my x86 bootloader to call c.

  • @FalcoGer
    @FalcoGer Жыл бұрын

    a reference is a pointer, except it's treated as the non pointer type by the compiler. the compiler will compile a reference to exactly the same bytecode as a pointer. personally I don't like them because they abstract the fact that a function may alter the reference. references are okay if they are declared const, and they are used in this manner to avoid costly copying of data with copy constructors, and instead just a 4 byte pointer is passed instead. of course passing a const pointer is also an option, but that just involves cluttering the code up with pointless dereferencing, making it less readable. const is also just a compiler check, by the way. there is no assembly instructions indicating that a value is not to be altered.

  • @ebebebeb7283
    @ebebebeb7283 Жыл бұрын

    thanks for this video, i'd been wondering what those were :)

  • @Mnogojazyk
    @Mnogojazyk Жыл бұрын

    Thanks for the nice, succinct explanation.

  • @jordanlapointe4690
    @jordanlapointe4690 Жыл бұрын

    subbed, thank you for this explanation. I'm always gonna remember "references are just spicy pointers".

  • @zamf
    @zamf Жыл бұрын

    The difference between pointers and references is mostly conceptual. A pointer is an object which holds an address to another location in memory. A pointer points to a value. A reference on the other hand should be though of as just another name for the same variable. An alias. It doesn't "point" to the variable. It *is* the variable. References should be considered a high-level construct, which only exists in code and not in the actual binary, while pointers exist as symbols in the binary. This is after turning on optimizations. Without optimizations references are just converted to pointers in the binary as we saw in the video. Of course, if a reference can outlive its scope (i.e. it is a member of a class or a lambda, etc.) then the compiler automatically converts it to a pointer and then it starts appearing as a pointer in the binary. But this is an exception. Most of the time references live inside of a specific scope and they act as just a different name for the variable they're referencing.

  • @flaviorodriguez8594
    @flaviorodriguez85947 ай бұрын

    My kid is learning how to code and I tried hard to explain to him the difference but your video is priceless, I'm showing it to him right now! thank you for that, have a long life and success! great video!

  • @bilalshaikh6603

    @bilalshaikh6603

    Ай бұрын

    How old is your kid?

  • @flaviorodriguez8594

    @flaviorodriguez8594

    Ай бұрын

    @@bilalshaikh6603 12y

  • @ArtykomHry
    @ArtykomHry Жыл бұрын

    note that one of the differences would be that the address of "rX" in your example would be the same as the address of "x", while the address of the "pX" would differ (as it points to the location of the pointer)

  • @anon_y_mousse
    @anon_y_mousse Жыл бұрын

    I think it was when I first learned about r-value references that I really started to hate C++. I was rather indifferent to it before that, but that, that is what made me hate it.

  • @timwong91198
    @timwong91198 Жыл бұрын

    My man, you have taught me more than my whole degree

  • @Eggman890
    @Eggman8905 ай бұрын

    The biggest benefit to references is they offer a kind of contract that tells the external code that the "ptr" cannot be null. This means that anything which is passed a reference (by return or function parameter) can safely use it without the need for any null checks.

  • @iwakeupsad
    @iwakeupsad Жыл бұрын

    That was ... just great. So great.

  • @raghavantncv5380
    @raghavantncv53809 ай бұрын

    Bro awsome content❤❤❤❤

  • @wojtekdudek2374
    @wojtekdudek237417 күн бұрын

    One significant advantage of using C++ references is the ability to reassign the pointers themselves through a function, rather than merely modifying the memory to which the pointers point. Consider the following example: template void set_null(const T*& ptr) { ptr = nullptr; } In this example, the function set_null directly sets the pointer itself to nullptr (or NULL in C, 0). This syntax is much cleaner and more straightforward compared to the rather complicated macros you would need to define in C to achieve similar functionality. Additionally, using functions like this scales better with complexity; as the function grows larger, macros become less manageable and maintainable, whereas the function approach remains clear and concise, at least in some part.

  • @aaaaanh
    @aaaaanh Жыл бұрын

    The mad thing for me was I only started to understand reference and pointer in C after I finished learning assembly 😭

  • @TECHN01200
    @TECHN01200 Жыл бұрын

    As much as I prefer c++ over c just for some of the quality of life attributes it brings (some of the new stuff in c++ is backwards, but whatever), I prefer pointers over references. I feel as though they are better signposted that "hey, something else might just change with this pointer". I say this because when you touch a pointer, you either are using an asterisk to access the value or you are using arrow notation to access a field.

  • @ericbwertz

    @ericbwertz

    6 ай бұрын

    The problem with unconstrained pointers is that they can take away a number of optimizations that the compiler may be able to do that would otherwise be safe to do if it only knew it was OK to do so. References are more like a sharpshooter than Yosemite Sam, so it's safer to be in the presence of the former than the latter.

  • @williamdrum9899
    @williamdrum9899 Жыл бұрын

    The thing I don't like about pointers is when you have to have a pointer to a specific memory address, the syntax is confusing. I can't remember it off the top of my head but I think it's like (*(int*)) 0xDEADBEEF or something like that. In assembly you would just use "dword ptr" which makes so much more sense

  • @tusharagarwal5306
    @tusharagarwal53064 ай бұрын

    Lol, I refreshed the video multiple times because I thought the first 2 secs clip was an ad.

  • @jamescraft5300
    @jamescraft53003 ай бұрын

    ty bro

  • @zemlidrakona2915
    @zemlidrakona2915 Жыл бұрын

    Personally I use pointers more often than references. I like the fact that with a pointer you can look at the code and know it's not a normal variable, without looking around for the declaration. I do often use references for passing stuff in a out out of functions however. I especially like references to pointers in that regard. They also come in handy for operator overloading, which if memory severs me, is why they were added to the language to begin with.

  • @jamesking2439
    @jamesking24395 ай бұрын

    References are one of the few C++ features I really do appreciate.

  • @mastershooter64
    @mastershooter6410 ай бұрын

    Writing int &var instead of int& var is heresy.

  • @NoodleBerry
    @NoodleBerry4 ай бұрын

    My compiler helpfully tells me if I try to return a local reference so that's nice

  • @martingeorgiev999
    @martingeorgiev999 Жыл бұрын

    Special reference properties like prohibiting NULL values makes references good for library code. In order to achieve the same optimizations in C you have to use compiler attributes like "nonnull" which is inconvenient because most attributes are compiler specific. That is, they are not in the standard.

  • @arunkrishna1854
    @arunkrishna1854 Жыл бұрын

    Any projects you'd suggest to get better at rust (I'm a pentester,red teamer and looking to get into more of the rust's system stuff)

  • @Supakills101
    @Supakills101 Жыл бұрын

    I once read "A reference is essentially a const pointer that is immediately de-referenced".

  • @itsawonderfullife4802
    @itsawonderfullife48024 ай бұрын

    References used to confuse me when I first learnt C++ and boy they are confusing! Because references are really (=syntactic sugar for) pointers but which are used like the data variables to which they point! They are supposed to make working with pointers, safer and more intuitive, but do they?

  • @michaeledwardharris
    @michaeledwardharris Жыл бұрын

    Very nice!

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    Thank you! Cheers!

  • @UnrealOG137
    @UnrealOG13710 ай бұрын

    You should do a video on compilers

  • @laenprogrammation
    @laenprogrammation Жыл бұрын

    References, when not parameters of functions (or when the functions get inlined), can be implemented without having pointers under the hood, because in many cases it's just an alias. Wheather the compiler understand the difference or not is up to it's programmer. G++ isn't the only c++ compiler out there, and i suspect it treats references as pointers in all cases for the sake of implementation simplicity. Just showing one example with no optimization and telling "they are the same" is not really proof of anything. I had a code to optimize with functions already inlined and when i started using references in stead of pointers, i had a real increase in speed (around 4%, because i had a lot of calls to as small function).

  • @yashwardhanchavan6153
    @yashwardhanchavan6153 Жыл бұрын

    The intro music is so good man, name?

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    Video description

  • @bob-ny6kn
    @bob-ny6kn Жыл бұрын

    "Give me C or give me death!" Wayne Gretzky Michael Scott

  • @Lugge1999
    @Lugge19994 ай бұрын

    if i have a function void add_to_var(int & x){...} and two variables int x = 0; int & rx = x; both calls work add_to_var(x) add_to_var(rx) even though the signature says that add_to_var expects the parameter x to be of type "reference to int", it also works with "int" i guess if I define a function to have a paramter of type "reference to int", then c++ just makes the parameter a reference to the argument inside the function body, without the given argument already having to be a reference itself. This logic also would explain why i can easily assign a reference to another reference: take this code snippet: int a = 0; int & b = a; int & c = b; c += 100; std::cout

  • @JanxZ
    @JanxZ Жыл бұрын

    "And the compiler knows what i mean!" Yeah...

  • @simonemicucci9222
    @simonemicucci9222 Жыл бұрын

    In short is a protected pointer? I can understand but appear not so much interesting if you know exactly what you want to do no?

  • @LowLevelLearning

    @LowLevelLearning

    Жыл бұрын

    I'm going to make a follow up video on design choices between pointers and references but in short, yeah a reference is just a pointer with controls on how you can access it. There are good use cases for pointers and references, but pointers can do both.

  • @dinobotpwnz

    @dinobotpwnz

    Жыл бұрын

    Since protections that make you have to think less are the only advantage, I'm really surprised references exist. The C++ FQA alludes to some different reason for why they were introduced but I'm still waiting for a video to explain that to me.

  • @simonemicucci9222

    @simonemicucci9222

    Жыл бұрын

    To be fair handle with reference and not a pointer is safer in 99% of code, have access to pointer too as alternative is a really good compromise for security and manipulation

  • @minirop

    @minirop

    Жыл бұрын

    @@dinobotpwnz it adds preconditions therefore the compiler can optimize the code better. If you fail to meet them (by having a reference to NULL for instance), it's your problem.

  • @XeroKimorimon

    @XeroKimorimon

    Жыл бұрын

    @@dinobotpwnz The reason why references exists in C++ is due to special member functions. Things like copy assignment, post increment etc. If we wanted to say do a copy assignment, it might end up being expensive to copy the whole object into the operator=() function, and we can't take a pointer to an object in operator=() because what would it even mean to do something like Foo f1; Foo f2; f2 = &f1; Are we trying to make a Foo* and assign it to f1? but that can't be, because f2 is clearly a Foo, did you mean to make it a Foo*, or is it really just a Foo that has opeartor=(Foo*) defined? It's really hard to tell, so they created references so it's much simpler to tell you intended to do f2 = f1 and not f2 = &f1 where f2 is a Foo*

  • @adamkrawczyk9261
    @adamkrawczyk9261 Жыл бұрын

    what about in functions? would there be literally no difference if you used a refrence or a pointer unless you wanted to change the pointer/refrence mid function

  • @U20E0

    @U20E0

    Жыл бұрын

    yes

  • @XxDTownxX91

    @XxDTownxX91

    Жыл бұрын

    If your function takes a reference as a parameter, it's guaranteed to not be null

  • @U20E0

    @U20E0

    Жыл бұрын

    @@XxDTownxX91 i did not consider that. built-in compile-time null prevention. So not yes

  • @minirop

    @minirop

    Жыл бұрын

    No differences, but someone could be pedantic by saying you can reassign the pointer parameter (i.e. pX = &another_int) but since a pointer is a variable in itself, you are not modifying the original pointer passed to the function therefore it's unnecessary/useless.

  • @catostre

    @catostre

    Жыл бұрын

    You can't index or increment a reference, so if I wanted to implement strlen() I would use a pointer

  • @dartusmin8924
    @dartusmin8924 Жыл бұрын

    A *reference* can actually be a null reference, but it is considered an undefined behavior by The Standard. Consider the following code: _auto& f = *((std::fstream*)nullptr);_ _f

  • @davidmccormack99

    @davidmccormack99

    Жыл бұрын

    Yep, my standard demo program whenever anyone says that a reference can’t be null is: int main() { auto& result = *(int*)nullptr; return result; }

  • @n00blamer

    @n00blamer

    Жыл бұрын

    @@davidmccormack99 It can be null, but as mentioned that is UB, so you don't have a _correct_ C++ program.

  • @davidmccormack99

    @davidmccormack99

    Жыл бұрын

    @@n00blamer Agreed, and in a simple example like I gave, correctness is something that is easy to make a judgment on. But in a complex system that’s not so easy. Consider a utility library (.dll or .so) that is dynamically loaded at runtime and has a function in its exported interface that accepts an int&. That function is correct to assume that the reference is non-null and yet it can fault at runtime due to a defect in the caller. Sometimes in these circumstances, I have wrapped the access to the reference in SEH (MSVC only).

  • @Tibor0991

    @Tibor0991

    Жыл бұрын

    @@davidmccormack99 and this is why you must ONLY write C++ code with -Werror always on.

  • @milo20060
    @milo20060 Жыл бұрын

    So basically both are referencing the x but the reference is a bit more restrictive by only having able to reference one while pointer can point to a pointer.. But then reference might be a bit more efficient. Yea probably got it now.

  • @morekozhambu
    @morekozhambu2 ай бұрын

    Reference and Pointer exist as constructs only within C++. Assembly is agnostic to this and everything is Register value. So cannot compare 1 to 1 though both may be implemented similarly.

  • @jan-lukas
    @jan-lukas Жыл бұрын

    In my experience you should use references any time you don't deal with dynamically allocated memory. That should either be done using unique_ptr, or if you're a madlad, raw pointers

  • @SkyyySi
    @SkyyySi Жыл бұрын

    Why do you assemble your code to then immediately disassemble it again? Just use "gcc -S", it will output the assembly code.

  • @mogenshansen7210
    @mogenshansen72103 ай бұрын

    Good, low level explanation. Reference was originally added to C++ to support operator overloading. Otherwise what type should operator=, operator== and operator+ take to have a natural syntax ? From the C++ Core Guidelines for function argument type (appr): use (const) reference when there has to exist an object (no null), use pointer when there can be zero or one object (not array - multiple object).

  • @MrAbrazildo
    @MrAbrazildo11 ай бұрын

    Pros: better syntax and tied to the same address, so it avoids a bug by change its destination. So it's recommended to use it whenever possible. Cons: don't take it as an alternative name, because you will depend on the compiler to optimize that away. It's better to use a macro for that matter. 0:11, it's quite the opposite: since it's more robust, you navigate through safer waters. And if you spend some time improving it, it'll become ever safer. It's only when you are making a mess is when it can become even unsafer than C.

  • @sreejishnair5922
    @sreejishnair5922 Жыл бұрын

    What does that mean that you have less overhead to use them? I didn't understand that part

  • @harshithgowda6227
    @harshithgowda622711 ай бұрын

    which software do you use for coding C++ on mac?

  • @maksymiliank5135
    @maksymiliank5135 Жыл бұрын

    You only scratched the surface. const references are so much more powerful in a sense that you can assign temporary objects to them. You cannot do this with pointers

  • @unrealdevop
    @unrealdevop3 ай бұрын

    3:14 You said that you can't assign a reference to a reference. But when you pass in a reference to a function that takes in a reference...how is that not the same as assigning a reference to a reference? That part is really confusing me because I'm used to thinking about pass-by-value in terms of a = b which copies the value from one to another. So naturally I'm thinking of passing in a value as '&b = a' where a is a reference.

  • @volbla
    @volbla Жыл бұрын

    So it's a pointer with all the pointer syntax abstracted away. That's pretty cool.

  • @n00blamer

    @n00blamer

    Жыл бұрын

    It's even cooler! Binding a reference to non-existing object is UB, so once you see a reference parameter you don't need go be worrying if it is pointing to a null, or non-existing object. A reference is always valid. The reasoning behind adding references was more about syntactic convenience which allowed new parameter passing tricks making the language more convenient. Those in the Functional camp of programming of course hate pointers and references because anything within scope is mutable from another thread but this is another discussion.

  • @valizeth4073

    @valizeth4073

    Жыл бұрын

    No, a pointer and a reference are conceptually and semantically different things. It's irrelevant if references are realized as pointers since it's an implementation detail. A pointer points to something, a reference aliases something.

  • @volbla

    @volbla

    Жыл бұрын

    @@valizeth4073 Implementation is what i'm interested in. I want to understand what's going on under the hood, because that helps me understand its use and usage.

  • @turner7777
    @turner7777 Жыл бұрын

    I can summarize it in one sentance: - Reference is literally another name for the original variable, they ARE the same thing, just with different names

  • @mareknetzel
    @mareknetzel Жыл бұрын

    More!

  • @YounessChaaibi
    @YounessChaaibi Жыл бұрын

    does reference take an additional memory as pointers ?

  • @sandipdas7206
    @sandipdas7206Күн бұрын

    Thanks for the treat now references aren't complicated either

  • @euler4513
    @euler4513 Жыл бұрын

    A reference is basically a const TYPE * that can’t be null yeah?

  • @97CelticPredator
    @97CelticPredator Жыл бұрын

    can you do a video on classes?

  • @01001000010101000100
    @01001000010101000100 Жыл бұрын

    I don't quite get it how it is "easier" to use. I think they are unnecessarily confusing. First we put some restrictions on a pointer IDK, to prevent an oblivious user from shooting themselves in the foot, but at the same time the variable pretends a local variable so the user can shoot themselves in the foot anyway forgetting it's a pointer, because it's being a pointer (or a reference) is hidden (because like definition can be off the screen at the moment)... Weird. But useful anyway. Maybe the syntax is a little confusing, but it makes sense to have a kind of read-only pointers that serve a particular purpose that are distinct from regular general-purpose pointers.

  • @scowell
    @scowell Жыл бұрын

    Now that I know about references... they piss me off!

  • @huntabadday2663
    @huntabadday2663 Жыл бұрын

    I work with assembly for fun, I don't think pointers are an issue for me.

  • @dickheadrecs
    @dickheadrecs Жыл бұрын

    nice demonstration. c++ becomes WAY less mysterious when you can read assembly. but at that point you may as well write your own compiler and use any syntax you want 😆

  • @mastershooter64

    @mastershooter64

    10 ай бұрын

    the thing that sucks is it's almost impossible to write a fully functional C++ compiler D: even teams of dozens of smart compiler engineers take several years to build one.

  • @luigidabro
    @luigidabro4 ай бұрын

    Mutable refs are illegal. I just need to know when a func is changing the args

  • @ignacioariellopez8491
    @ignacioariellopez84915 ай бұрын

    Question for anyone that might happen to be here after a year. I get now this is C++, but the whole int &ri = i; is still valid C code? And if so, how does it work? Never came across it when i was studying and i just blew my mind trying to figure out differences to int *ri = i; therefore my question if its still valid C or C++ exclusive.

  • @jawwad4020
    @jawwad40202 ай бұрын

    Would the reference have a memory different address from the original variable ? I thought references are aliases, unlike pointers.

  • @charlesmayberry2825
    @charlesmayberry28253 ай бұрын

    I wouldn't say a reference is a "spicy pointer" it's a special type of pointer for sure, I always thought of them as "pointers with some protections" Which is great, there are several situations where I have made a mistake that would be allowed using a pointer but would have crashed at runtime, using a reference it goes "you can't do that" at compile time, look at the code and go "oh that's dumb what was I thinking" fix it and move on. Basically... what is a reference? a pointer that shortens my debugging time lol

  • @user-bi1vi6nm2o
    @user-bi1vi6nm2o Жыл бұрын

    Can you make a video to play with DAC on raspberry pi (pure C).. i saw someone make a fm radio transmitter using raspberry pi 😁

  • @akaikangaroo
    @akaikangaroo Жыл бұрын

    So, can we have a reference to pointer?🤔

  • @coder436
    @coder436 Жыл бұрын

    Which song is playing in the background

  • @briandawley7808
    @briandawley78087 ай бұрын

    Is there a point to using references outside of passing arguments to functions? When I was learning C++, I learned it as, basically, when you're passing an argument, you can either pass a copy of the object (which can only be modified locally, doesn't impact "the object" that was passed outside of the function to which it was passed), or you can pass the object itself. If all you want is the ability to use the *value* of the object, but not manipulate the object itself, use "foo(obj X)." If you want the object itself (i.e., direct access to the object, so you can change it and it will stay changed outside of the current function), pass a reference, i.e., "foo (obj &X)." That said, this was over 20 years ago, so I may not be remembering correctly, haha.

  • @xmvziron
    @xmvziron Жыл бұрын

    Never thought I'd say this but imma stick with my pointers.

  • @abuk95
    @abuk95 Жыл бұрын

    Double reference `&&variable` is still a mystery, though.

  • @anon_y_mousse

    @anon_y_mousse

    Жыл бұрын

    It's an r-value reference.

  • @abuk95

    @abuk95

    Жыл бұрын

    @@anon_y_mousse Now both &&variable and r-value references are mystery, lol.

  • @anon_y_mousse

    @anon_y_mousse

    Жыл бұрын

    @@abuk95 The &&var is an r-value reference. It's used for std::move() semantics so that it doesn't cause an unnecessary construction or allocation.

  • @n00blamer

    @n00blamer

    Жыл бұрын

    It's already said it's r-value reference, but why!? The reasoning is that when "they" wanted move construction in C++ they needed a syntax, and decided that && will be move. The std::move turns object into r-value (&&) which matches before &, very ugly hack, LOL, but it works. Now C++ has move construction. The End.

  • @izagawd
    @izagawd2 ай бұрын

    so a reference is just syntactic sugar

  • @Morstius
    @Morstius Жыл бұрын

    Now do the C++/CLI charet (^) :P Neat video btw.

  • @davidmccormack99
    @davidmccormack99 Жыл бұрын

    Nit-picking C++ guy says: if it is C++ you should be including instead of :)

Келесі