Back to Basics: Const as a Promise - Dan Saks - CppCon 2019

Sdílet
Vložit
  • čas přidán 26. 05. 2024
  • CppCon.org
    Discussion & Comments: / cpp
    Presentation Slides, PDFs, Source Code and other presenter materials are available at: github.com/CppCon/CppCon2019
    -
    Back to Basics: Const as a Promise
    The const qualifier has various uses in C++. One of the most valuable uses is in declaring function headings that constrain the effects of function calls. Using const appropriately can reduce bugs and development time by turning potential run-time errors into compile-time errors that are much easier to find and correct. Using const can even reduce your program’s code size and execution time.
    Despite these benefits, too many C++ programmers still use const reactively rather than proactively. That is, they tend to add const as needed to quell compiler error messages, rather than design const in as they code. To get the most out of const, programmers really need to understand (1) when and where to place const in declarations, (2) when to leave it out entirely, and (3) how type conversions involving const behave.
    The key insight about const is to understand const as a promise-a promise not to modify something. This session explains the real meaning of that promise and how that insight can guide you in declaring function parameters and return types. It also explains why you shouldn’t declare by-value parameters and return types as const, why overloading on const is such a useful and ubiquitous idiom, and why it is meaningful to declare constexpr member functions as const.
    -
    Dan Saks
    Dan Saks is the president of Saks & Associates, which offers training and consulting in C and C++ and their use in developing embedded systems. Dan used to write the “Programming Pointers” column for embedded.com online. He has also written columns for numerous print publications including The C/C++ Users Journal, The C++ Report, Software Development, and Embedded Systems Design. With Thomas Plum, he wrote C++ Programming Guidelines, which won a 1992 Computer Language Magazine Productivity Award. Dan has taught C and C++ to thousands of programmers around the world. He has presented at conferences such as Software Development, Embedded Systems, and C++ World. He has served on the advisory boards of the Embedded Systems and Software Development conferences. Dan served as secretary of the ANSI and ISO C++ Standards committees and as a member of the ANSI C Standards committee. More recently, he contributed to the CERT Secure C Coding Standard and the CERT Secure C++ Coding Standard.)
    -
    Videos Filmed & Edited by Bash Films: www.BashFilms.com
    *-----*
    Register Now For CppCon 2022: cppcon.org/registration/
    *-----*
  • Věda a technologie

Komentáře • 30

  • @rafalmichalski4893
    @rafalmichalski4893 Před 4 lety +44

    I think on slide 52 should be "wi(ci);" to break promise :-) Anyway great talk. Thank you Dan for clarifying such topics.

  • @groaningmole4338
    @groaningmole4338 Před 4 lety +6

    Saks' talks are useful for re-learning all those little details that are so easily forgotten. (I programmed in C++ for over 10 years, but switched mostly to Python about 2 years ago, which has given me time to forget things.)

  • @johnheaney3349
    @johnheaney3349 Před 2 lety +2

    This all seems very important when using C++ to write complex systems. But there is also a very specific purpose to const when writing firmware that executes from non-volatile memory (flash). NVM or ROM is in the same address space as RAM. When you define an object the initial value is placed in a linker section that exists in flash. Then at program initialization all of the values in that linker section are copied to RAM and the ROM copy is never looked at again. Defining an object as const means that the initial value in ROM is THE value. It is not copied to RAM, but accessed directly in ROM. That saves RAM, which is generally a precious resource in firmware applications. It also saves time at startup, not having to do the copy.
    If you're writing a computer application it doesn't matter. Everything gets copied to RAM. It's an important distinction in embedded systems where the code is executing in ROM and constant data is referenced in ROM, as well.
    I should be clear that I use C for firmware development, but there is no distinction between C and C++ on this point, so I think there is some merit to pointing this out when introducing the significance of const.

  • @ChrisBNisbet
    @ChrisBNisbet Před rokem +1

    Marking pointers as const in function _declarations_ doesn't mean much/anything, but in the function _definition_ it's a different story. Making a function pointer parameter const means I can't inadvertently change the pointer to point at some other address, and I will find out at compile time if that happens (exactly like with a regular const pointer variable). This has saved me making runtime errors more than once.

  • @ibrahim47
    @ibrahim47 Před 4 lety +4

    Great talk, those consts used to give me a headache. but it is much clearer now.

  • @kamilziemian995
    @kamilziemian995 Před rokem

    People like Dan Saks are like guiding light in the dark forest of the C++.

  • @mohammadmahdifarnia5358
    @mohammadmahdifarnia5358 Před rokem +1

    Always appreciate dan talks 👍

  • @guykeren9666
    @guykeren9666 Před rokem

    Great slides and talk! I finally really understand why I 'just know' what I know

  • @speakingmia7298
    @speakingmia7298 Před 4 měsíci

    The last few minutes delivered a lot of interesting examples which I hope could be more elaborated.

  • @lamug
    @lamug Před 3 lety +3

    Thank you! I learned a lot.

  • @creapermann6356
    @creapermann6356 Před 2 lety +1

    Great talk

  • @ABaumstumpf
    @ABaumstumpf Před rokem

    Slide 20 - but... that is not operator precedence - that is not a thing in the standard. it is just the way that "declerators" and "direct-declarators" are specified that specify what syntax matches.
    And the first syntax to match is the one for declaring an array: "direct-declarator1 [...]" - and then the next match is for the type-identifier making the type of the array-elements pointers.

    • @speakingmia7298
      @speakingmia7298 Před 4 měsíci +1

      I am confused too. If it's a precedence thing, then the "pointer to an array" should win.

  • @glaysonpatricio
    @glaysonpatricio Před 4 lety +1

    great talk ... but what about const as a return from a function? what are the best practices in that case ?

    • @chiliu9304
      @chiliu9304 Před 3 lety +3

      operator [] overloading shows const as a return from a function

  • @user-zp3nd6ht8v
    @user-zp3nd6ht8v Před 4 lety

    I can not find the slides of this video, anyone else?

  • @think2086
    @think2086 Před 2 lety

    Great talk. We need more of this kind of stuff.
    I don't understand slide 20.
    He states that [ ] has a higher precedence than *, but then says "therefore x is an array of pointers." That seems the OPPOSITE of what it should be. Wouldn't * having higher precedence result in that? Shouldn't it be the case that if [ ] has a higher precedence, that it's a pointer to an array? Higher precedence refers to the associativity of operators. If the operator has higher precedence, it's more "closely bound" to that part of the expression, so therefore if [ ] has higher precedence, shouldn't it be "here's an array... and here is a pointer to that array?"
    This seems fundamentally backwards.
    Even the example given using addition and multiplication supports this: a + b * c = a + (b * c)
    Here, the b and c are more closely associated, then the a+ comes in later, all because multiplication has a higher precedence. So if [ ] has a higher precedence than pointer *, shouldn't it be "a pointer to an array?" I know that's not right however, which is why it seems like pointer * should have a higher precedence than [ ], not the other way around.
    It seems like he used the associativity of "of" in the grammar of English to justify this, but that's quite subtle. "x is an array OF," such that linguistically, he has "x" closer--so to speak--to "array," than to "pointer to." But that's not at all how I think about it, and I think that's because I think about it more in terms of "who contains who?" When you say [ ] has higher precedence than pointer *, to my mind that sounds like you're saying "x[ ]" first, and "*" second, with the second thing containing the first thing: (pointer to (an array)). See how the arrayness is more nested? Lower precedence operators generally "contain"/"distribute over" higher precedence after all.
    Super confusing.
    Then again, maybe that's actually correct to think more linguistically in this case. In which case I think the addition and multiplication example actually confuses more than it illuminates.

    • @ABaumstumpf
      @ABaumstumpf Před rokem

      Cause there is no precedence for declarations (or for any operator for that matter) specified in the C++-language.
      It is a horrendous mess that basically only makes sense to people that are already too used to it.
      the simple "int *a[5]" shows quite nicely that there is no such thing as precedence here:
      Pointer-declarations must be "pointer to type" - but "[5]" is not a type and thus it is not a pointer-declaration. But for array-declaration it works - "[5]" declares and array with 5 elements of type "int *" with the name "a".
      and "int (*a)[5]" - the "()" is matched first, with makes "*a" "a pointer to" - then "[5]" an array of 5 elements - "int" of type int.
      Yeah - confusing as hell.
      learn.microsoft.com/en-us/cpp/c-language/declarators-and-variable-declarations?view=msvc-170

  • @treyquattro
    @treyquattro Před 4 lety +2

    the examples seemed a little contrived, particularly as basic_string already defines size() as const-qualified and operator[] has two variants, one returning reference to const type and one returning non-qualified reference to type:
    reference operator[]( size_type pos ); (1)
    const_reference operator[]( size_type pos ) const; (2)
    en.cppreference.com/w/cpp/string/basic_string/operator_at
    size_type size() const; (until C++11)
    size_type size() const noexcept; (since C++11)
    size_type length() const; (until C++11)
    size_type length() const noexcept; (since C++11)
    en.cppreference.com/w/cpp/string/basic_string/size
    Dan may have been referring to non-STL implementations of string e.g., but I thought it might have been useful to point that out.

    • @jackofnotrades15
      @jackofnotrades15 Před 3 lety

      yeah, he was not taking stl approach, it was just a generic discussion. Especially if somebody makes their own string class they might not make size() const.

    • @ohyonghao
      @ohyonghao Před 3 lety +1

      I don't get complaints about contrived examples. He's showing us something we are familiar with and explaining why it is the way it is. He could waste 15 minutes showing us some real world example and explaining the example and giving us context and motivation for why we would want this, but that distracts from the actual point of the talk. So great job on pointing out stl is doing it right.

  • @philippjungkamp3760
    @philippjungkamp3760 Před 2 lety

    Oh my god! typedef is a non-type declaration specifier?!
    Just tried some weird stuff....
    volatile typedef int reg;
    int set_reg(reg * dest, int val) {
    return *dest = val;
    }
    reg * is indeed a pointer to a volatile int...

  • @pedromiguelareias
    @pedromiguelareias Před 2 lety

    For value semantics of non-intrinsics I view const-correctness as a waste of time. Only use it in copy constructor and copy assignment operators. The rest becomes silly for daily use.

  • @lexer_
    @lexer_ Před 3 lety +2

    God is he beating a dead horse with const value types in arguments. Almost 20 minutes of this talk consist of this one point. The rest is great and I am thankful to finally have a clear and simple summary of all these unintuitive rules. Especially the last part was very enlightening. But please, repeating something that is obviously common sense over and over has no place in a talk like this.

    • @daest07
      @daest07 Před 2 lety +5

      its a back to basics talk, the whole point is to go slow with these.

    • @think2086
      @think2086 Před 2 lety +4

      DIsagree. There is subtlety and tons of bugs resulting from a lack of deep understanding on these topics. C++ is hard. You've had too much coffee this morning perhaps? Use the youtube speed feature to double when you need to.
      Most talks are far too fast, which is far more annoying.