what even is a "reference"?

แชร์
ฝัง
  • เผยแพร่เมื่อ 1 ต.ค. 2024

ความคิดเห็น • 271

  • @LowLevel-TV
    @LowLevel-TV  2 ปีที่แล้ว +112

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

    • @user-mz8qj7bz8h
      @user-mz8qj7bz8h 2 ปีที่แล้ว +1

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

    • @SKBotNL
      @SKBotNL 2 ปีที่แล้ว +2

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

    • @capitalists1526
      @capitalists1526 2 ปีที่แล้ว +2

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

    • @SKBotNL
      @SKBotNL 2 ปีที่แล้ว

      @@user-mz8qj7bz8h Found it! It's Strange Stuff by Matt Harris th-cam.com/video/UP457lLBZls/w-d-xo.html

    • @piotrkozbial8753
      @piotrkozbial8753 ปีที่แล้ว +3

      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 2 ปีที่แล้ว +275

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

    • @Brad_Script
      @Brad_Script 3 หลายเดือนก่อน +1

      array indexes will dereference a pointer, that's really the only difference

  • @joey199412
    @joey199412 2 ปีที่แล้ว +301

    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 2 ปีที่แล้ว +20

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

    • @ghosthunter0950
      @ghosthunter0950 ปีที่แล้ว +2

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

    • @mastershooter64
      @mastershooter64 ปีที่แล้ว +2

      "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 ปีที่แล้ว +5

      ​​@@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

    • @Abcd-ti9wv
      @Abcd-ti9wv 2 หลายเดือนก่อน

      there s no guarantee reference are not null, you can do int& Ref = *(int*)(nullptr)

  • @teranyan
    @teranyan ปีที่แล้ว +28

    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 ปีที่แล้ว +42

    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 2 ปีที่แล้ว +201

    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 2 ปีที่แล้ว +3

      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 2 ปีที่แล้ว +2

      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 2 ปีที่แล้ว +2

      How exactly can you implement references other than pointers?

    • @9SMTM6
      @9SMTM6 2 ปีที่แล้ว +1

      @@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 2 ปีที่แล้ว

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

  • @metal571
    @metal571 2 ปีที่แล้ว +88

    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

    • @LowLevel-TV
      @LowLevel-TV  2 ปีที่แล้ว +9

      YAY 🖥

    • @nishanth6403
      @nishanth6403 2 ปีที่แล้ว +5

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

  • @minikindaniil99
    @minikindaniil99 2 ปีที่แล้ว +36

    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 2 ปีที่แล้ว +6

      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.

  • @filipcimo998
    @filipcimo998 2 ปีที่แล้ว +139

    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 2 ปีที่แล้ว +22

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

    • @gustawbobowski1333
      @gustawbobowski1333 2 ปีที่แล้ว +3

      What's the actual use?

    • @ronaldweasly561
      @ronaldweasly561 2 ปีที่แล้ว +16

      @@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 2 ปีที่แล้ว +15

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

    • @claywynn9837
      @claywynn9837 2 ปีที่แล้ว +9

      @@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-gcc
    @usr-bin-gcc 2 ปีที่แล้ว +13

    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.

  • @mareknetzel
    @mareknetzel 2 ปีที่แล้ว +35

    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.

  • @VTdarkangel
    @VTdarkangel 2 ปีที่แล้ว +111

    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 ปีที่แล้ว +19

      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 ปีที่แล้ว +17

      ​@@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 10 หลายเดือนก่อน +10

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

    • @JurekOK
      @JurekOK 10 หลายเดือนก่อน +2

      @@ericbwertz :-) Good one!

    • @jaimeguzman4655
      @jaimeguzman4655 9 หลายเดือนก่อน +1

      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

  • @ohwow2074
    @ohwow2074 2 ปีที่แล้ว +14

    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).

  • @cno9984
    @cno9984 2 ปีที่แล้ว +12

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

  • @ABaumstumpf
    @ABaumstumpf 2 ปีที่แล้ว +4

    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.

  • @jaysistar2711
    @jaysistar2711 2 ปีที่แล้ว +20

    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.

  • @mastershooter64
    @mastershooter64 ปีที่แล้ว +3

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

  • @thebestwizz
    @thebestwizz ปีที่แล้ว +9

    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.

  • @FalcoGer
    @FalcoGer ปีที่แล้ว +2

    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.

  • @CanoTheVolcano
    @CanoTheVolcano 2 ปีที่แล้ว +7

    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

  • @mikegofton1
    @mikegofton1 2 ปีที่แล้ว +8

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

    • @LowLevel-TV
      @LowLevel-TV  2 ปีที่แล้ว

      Glad it was helpful!

    • @gustawbobowski1333
      @gustawbobowski1333 2 ปีที่แล้ว

      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 2 ปีที่แล้ว +2

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

  • @RobertGuilman
    @RobertGuilman 2 ปีที่แล้ว +6

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

    • @LowLevel-TV
      @LowLevel-TV  2 ปีที่แล้ว +1

      Glad you enjoy it!

  • @rohanjoshi8785
    @rohanjoshi8785 2 ปีที่แล้ว +4

    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 ".

  • @m4rt_
    @m4rt_ ปีที่แล้ว +3

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

  • @maksymiliank5135
    @maksymiliank5135 2 ปีที่แล้ว +2

    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

  • @simonemicucci9222
    @simonemicucci9222 2 ปีที่แล้ว +6

    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?

    • @LowLevel-TV
      @LowLevel-TV  2 ปีที่แล้ว +5

      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 2 ปีที่แล้ว +1

      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 2 ปีที่แล้ว

      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 2 ปีที่แล้ว +3

      @@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 2 ปีที่แล้ว +2

      @@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*

  • @dandymcgee
    @dandymcgee 2 ปีที่แล้ว +2

    So basically, references are pointless.
    Get it? ......... cus they're not pointers.......

  • @piotrkozbial8753
    @piotrkozbial8753 ปีที่แล้ว +1

    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.

  • @itsawonderfullife4802
    @itsawonderfullife4802 8 หลายเดือนก่อน +1

    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?

  • @zamf
    @zamf ปีที่แล้ว +1

    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.

  • @akaikangaroo
    @akaikangaroo 2 ปีที่แล้ว +1

    So, can we have a reference to pointer?🤔

  • @TECHN01200
    @TECHN01200 ปีที่แล้ว +2

    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 10 หลายเดือนก่อน

      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.

  • @tusharagarwal5306
    @tusharagarwal5306 8 หลายเดือนก่อน +1

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

  • @aaron6807
    @aaron6807 2 ปีที่แล้ว +1

    Then comes std::ref and ruins everything

  • @joiscode3832
    @joiscode3832 2 ปีที่แล้ว +2

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

  • @ashenone5774
    @ashenone5774 2 ปีที่แล้ว +3

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

  • @laenprogrammation
    @laenprogrammation ปีที่แล้ว +1

    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).

  • @anon_y_mousse
    @anon_y_mousse 2 ปีที่แล้ว +1

    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.

  • @jan-lukas
    @jan-lukas 2 ปีที่แล้ว +5

    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

  • @adamkrawczyk9261
    @adamkrawczyk9261 2 ปีที่แล้ว +4

    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

    • @chri-k
      @chri-k 2 ปีที่แล้ว +1

      yes

    • @XxDTownxX91
      @XxDTownxX91 2 ปีที่แล้ว +8

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

    • @chri-k
      @chri-k 2 ปีที่แล้ว +3

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

    • @minirop
      @minirop 2 ปีที่แล้ว +1

      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 2 ปีที่แล้ว

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

  • @dartusmin8924
    @dartusmin8924 2 ปีที่แล้ว +2

    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

    • @Baile_an_Locha
      @Baile_an_Locha 2 ปีที่แล้ว

      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 2 ปีที่แล้ว

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

    • @Baile_an_Locha
      @Baile_an_Locha 2 ปีที่แล้ว

      @@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 ปีที่แล้ว

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

  • @SkyyySi
    @SkyyySi 2 ปีที่แล้ว +1

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

  • @Ownedyou
    @Ownedyou 2 ปีที่แล้ว +6

    C++ people are special! >:(

  • @codefire88
    @codefire88 2 ปีที่แล้ว +1

    The music is to loud

  • @unrealdevop
    @unrealdevop 6 หลายเดือนก่อน

    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.

  • @aaaaanh
    @aaaaanh 2 ปีที่แล้ว +1

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

  • @sandeepvk
    @sandeepvk 2 ปีที่แล้ว

    speaking slowly to explain a difficult concept doesn't help. An analogy would be bettet.

  • @Baile_an_Locha
    @Baile_an_Locha 2 ปีที่แล้ว

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

  • @wojtekdudek2374
    @wojtekdudek2374 4 หลายเดือนก่อน

    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.

  • @briandawley7808
    @briandawley7808 11 หลายเดือนก่อน

    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.

  • @poutineausyropderable7108
    @poutineausyropderable7108 10 หลายเดือนก่อน

    I prefer pointers. Some say the syntax is bad.
    I say, It's just a stronger Type.
    I hate implementing Linked List In Java or python.
    Am I changing the pointer, or the thing the pointer represent? It's hell.
    But by using pointers: It is always nice and clear.
    Also:
    object.data, object.next is so much better then
    object, object.next
    Fucking confusing syntax.

  • @mogenshansen7210
    @mogenshansen7210 7 หลายเดือนก่อน

    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).

  • @ignacioariellopez8491
    @ignacioariellopez8491 9 หลายเดือนก่อน

    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.

  • @charlesmayberry2825
    @charlesmayberry2825 7 หลายเดือนก่อน

    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

  • @morekozhambu
    @morekozhambu 5 หลายเดือนก่อน

    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.

  • @PieroUlloa
    @PieroUlloa ปีที่แล้ว

    Hmm, even though this video is a year old, I would like to point that in the last bit (at 5:27), where you said that references are spicy pointers, I think you should have said the opposite, ie. that pointers are spicy references.

  • @SageMadHatter
    @SageMadHatter 2 ปีที่แล้ว

    What’s with the space game music in the background? It distracts from your explanation

  • @gideonjonkers2683
    @gideonjonkers2683 3 หลายเดือนก่อน

    I have found that when you make a pointer that points to a reference, it has the same memory address as the original variable. How come? If the reference is loaded on to stack like a pointer then the pointer to the reference should give the address of the reference and not the original variable, right? Or does the complier just overwrite the pointer of a reference to be to the original variable?

  • @jawwad4020
    @jawwad4020 6 หลายเดือนก่อน

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

  • @steveokinevo
    @steveokinevo 2 ปีที่แล้ว

    correct they look the same under the hood, c++ hides all this within the mechanics of the compiler. clever little buggers. If you want to see some real C++ magic look into classes and objects (public/private) members, you will see some syntax wizardry at work here. People forget that most of the languages today have some association / relationship with C/C++, or have been coded from scratch using such tools. Peace.

  • @yashwardhanchavan6153
    @yashwardhanchavan6153 2 ปีที่แล้ว +2

    The intro music is so good man, name?

  • @scowell
    @scowell ปีที่แล้ว

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

  • @ericbwertz
    @ericbwertz 10 หลายเดือนก่อน

    "References are just spicy pointers"
    References are just bland, weak-ass pointers.

  • @izagawd
    @izagawd 6 หลายเดือนก่อน

    so a reference is just syntactic sugar

  • @jurgenblick5491
    @jurgenblick5491 5 หลายเดือนก่อน

    Why does C++Builder 11 have problems with this concept

  • @bob-ny6kn
    @bob-ny6kn ปีที่แล้ว

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

  • @paherbst524
    @paherbst524 2 ปีที่แล้ว

    How would this trigger c++ devs?
    It is what it is.

  • @luigidabro
    @luigidabro 8 หลายเดือนก่อน

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

  • @UmmadikTas
    @UmmadikTas 2 ปีที่แล้ว

    Dude what is up with that music on the background. It's too loud

  • @euler4513
    @euler4513 2 ปีที่แล้ว

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

  • @DominikLoeffler1
    @DominikLoeffler1 4 หลายเดือนก่อน

    Is it any surprise that they are the same under the hood? Everything stored will need to have an address

  • @bazoo513
    @bazoo513 ปีที่แล้ว

    So, references are just syntactic sugar for immutable pointers making it, frankly, less clear what is actually happening... (And, as some people point out, because their behaviour is far more limited, they give a compiler chance to produce better code and the programmer slightly less chance to shoot themselves in the foot.)
    (Obviously, I don't know C++.)

  • @sreejishnair5922
    @sreejishnair5922 ปีที่แล้ว

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

  • @momoz3063
    @momoz3063 2 ปีที่แล้ว +5

    please make the music quieter next video

  • @Aramizyera23
    @Aramizyera23 2 ปีที่แล้ว

    If I have been triggered by this can I be named C++ programmer?

  • @NoodleBerry
    @NoodleBerry 8 หลายเดือนก่อน

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

  • @shriram5494
    @shriram5494 ปีที่แล้ว

    Missing a lot of nuance, especially relating to move semantics.

  • @Uerdue
    @Uerdue ปีที่แล้ว

    So, a reference is just a pointer that takes longer to compile?

  • @MrAbrazildo
    @MrAbrazildo ปีที่แล้ว

    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.

  • @Adam_Lyskawa
    @Adam_Lyskawa 2 ปีที่แล้ว

    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.

  • @UnrealOG137
    @UnrealOG137 ปีที่แล้ว

    You should do a video on compilers

  • @williamdrum9899
    @williamdrum9899 2 ปีที่แล้ว

    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

  • @0xbinarylol
    @0xbinarylol 11 หลายเดือนก่อน

    & reference is cleaner version of * pointer nothing special.

  • @sandipdas7206
    @sandipdas7206 3 หลายเดือนก่อน

    Thanks for the treat now references aren't complicated either

  • @harshithgowda6227
    @harshithgowda6227 ปีที่แล้ว

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

  • @Eggman890
    @Eggman890 9 หลายเดือนก่อน

    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.

  • @jordanlapointe4690
    @jordanlapointe4690 ปีที่แล้ว

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

  • @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.

  • @user-bi1vi6nm2o
    @user-bi1vi6nm2o 2 ปีที่แล้ว

    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 😁

  • @jamesking2439
    @jamesking2439 9 หลายเดือนก่อน

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

  • @milo20060
    @milo20060 2 ปีที่แล้ว

    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.

  • @turner7777
    @turner7777 2 ปีที่แล้ว

    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

  • @ws9691
    @ws9691 2 หลายเดือนก่อน

    Awesome explanation - Thank You!!

  • @Spencer-r6r2l
    @Spencer-r6r2l 8 หลายเดือนก่อน

    You can write spaghetti code in any language.

  • @coder436
    @coder436 ปีที่แล้ว

    Which song is playing in the background

  • @coldblaze100
    @coldblaze100 2 ปีที่แล้ว +1

    Music credits pls dad

    • @LowLevel-TV
      @LowLevel-TV  2 ปีที่แล้ว

      In the description, I gotchu

  • @Supakills101
    @Supakills101 ปีที่แล้ว

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

  • @YounessChaaibi
    @YounessChaaibi ปีที่แล้ว

    does reference take an additional memory as pointers ?

  • @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)

  • @xmvziron
    @xmvziron 2 ปีที่แล้ว

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