C9 Lectures: Stephan T. Lavavej - Core C++

Stephan T. Lavavej: Core C++, 1 of n

Download this episode

Download Video

Description

In part 1, STL focuses on Name Lookup, which is a surprisingly complex process.

Remember Herb Sutter's great GotW post (#30, to be precise) on Name Lookup? Here's the problem from that post, to refresh your memory (Thanks to Herb for providing information like this on GotW!):

In the following code, which functions are called? Why? Analyze the implications?

namespace A {
      struct X;
      struct Y;
      void f( int );
      void g( X );
}

namespace B {
       void f( int i ) {
            f( i );   // which f()?
        }
        void g( A::X x ) {
             g( x );   // which g()?
        }
        void h( A::Y y ) {
             h( y );   // which h()?
        }
 }

We recommend you watch this entire episode before playing around with Herb's sample above (and don't read the GotW answer, either! That's cheating. Learn from STL. He's an outstanding teacher, as you know.)

Please supply feedback on this thread, especially as it relates to what you'd like STL to focus on in subsequent episodes. For part 2, STL will focus on Template Argument Deduction.

Tune in. Enjoy. Learn.

Embed

Format

Available formats for this video:

Actual format may change based on video formats available and browser capability.

    The Discussion

    • Spetum

      Welcome! STL.

      Thank you for new topics that I expect.

       

    • contextfree`

      Awesome.

    • x0d3

      Another c++ series, awesome ! 

    • grenangen

      This is great! 

    • codeman

      so cool, I admit these c++ series

    • Vivek kumar

      We welcome you!!!

      Thanks for beings with us.

    • LeeCampbell

      Cheers. As a C# dev this helped me understand the syntax (:: << etc) more than anything. Most of the rules seem quite similar to the C# rules which is nice.

      Good work.

    • kayvan

      Thank you for a wonderful presentation.  For your next episode on this topic would you cover these topics

      0) C/C++ run-time startup functions,lifecycle, ie: initialization, how C/C++ startup function calls your application's entry-point function

      1) Virtual functions and the Run time cost of virtual functions & dynamic binding.  

      2) forward declaration.  Forward declaration of template classes

      3) difference between 

      template <class T> MyClass

      template <typename T> MyClass

    • Marek

      Offtopic: About Chemists and Physicists: http://xkcd.com/435/

    • mfj

      Add a vote to Kayvan (1) Virtual functions :-)

    • AceHack

      I also would like to see forward declarations.  I'm also curious about typedef and as much as possible about the Preprocessor if that's considered part of the core c++.  Thanks.

    • Guest

      Great video STL

    • windev

      Great video STL. Can't wait to watch more episodes.

      Feel free to just go over each clause in the spec!

    • Carl

      Outstanding. A lot of STL's topics go over my head, but this is exactly along the lines of what I need. Very happy to see someone so knowledgeable explaining core concepts of the language!

    • Chris

      Excellent lecture.

      What I love about C++ is its complexity and that some operations in the language are undefined. This allows you to go even further than just learning C++. You can research C++.

    • Ivan

      I barely managed to watch this episode, but not because STL is bad but because I really dont care that much about language rules, but since STL is so cool I maganed to watch it.
      @STL
      1.Regarding episode 2 dont forgett to mention pointer paradox. I learned about it from a horrible horrible Di Gennaro's TMP book.
      2. Do you know why there arent trie_(multi)set and trie_(multi)map in boost or std? To obscure?
      3. One of the cool lectures (using TMP) would be solving this problem (if possible) :
      http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Dr-Graham-Hutton-Functional-Programming-Fundamentals-Chapter-11-of-13
      with TMP
      4. Explanation of some Boost TMP magic would be nice... maybe even you can get some cool boost guest lecturer :)
      5. Idioms are a cool topic imho. Like I said I dont care that much about lang rules, but I like learning idiomatic way of programming in language X.

    • tomkirbygre​en

      Another classic. I've been using this language for almost 18 years and Stephan clear up some of the name resolution stuff for me in this video. Looking forward very much to the template resolution stuff.

    • Guest

      This was a pretty great video, I actually program c++ for 5 years and I was not aware of argument lookup and name space alias syntax thank you STL and I hope this n seris continue to n == infint.
      I actually have one question when you std::cout something in c++ why don't you include just iostream and you include ostream too I think iosteam will provide the ostream functions and objects too.

    • Garp

      So I take it that the next standard library is ready to ship (at least the template part)?
      It's good to have you back, Stephan.
      Smiley

    • STL

      Thanks for watching, everyone. I'm always a little nervous when I spend 45 minutes talking to an empty room, because it's hard to tell whether I'm going too fast or too slow, too complicated or too simple. Your feedback really helps when targeting future episodes.

      LeeCampbell> As a C# dev this helped me understand the syntax (:: << etc) more than anything.

      I'm glad to hear that. My goal in all of these episodes is to give you a taste and a general overview of the topic, making it easier to understand other videos/articles/books.

      LeeCampbell> Most of the rules seem quite similar to the C# rules which is nice.

      "Wow, people in Britain speak a language that's really similar to America's!" :->

      kayvan> 0) C/C++ run-time startup functions,lifecycle, ie: initialization, how C/C++ startup function calls your application's entry-point function

      This is outside my area of expertise (as far as I'm concerned, magic invokes main()), but I bet Charles could ask our CRT maintainer, Mahmoud Saleh, to cover this.

      kayvan> 1) Virtual functions and the Run time cost of virtual functions & dynamic binding. kayvan> 2) forward declaration.  Forward declaration of template classes

      Got it. I was definitely planning to cover virtual functions (in particular, my favorite NVI idiom), but I had forgotten how important the subject of declarations versus definitions is. I'll cover that at the first available opportunity.

      kayvan> 3) difference between template <class T> MyClass [and] template <typename T> MyClass

      There is none! :-> (Only template template parameters care about typename versus class - and that is not a repeated word typo.)

      I personally prefer "typename", because "class" has confusing connotations (it does NOT restrict T to class types; int remains perfectly acceptable).

      AceHack> I'm also curious about typedef

      Cool. I'll see if I can cover this in an episode along with other smaller features. (Unfortunately I can't demonstrate C++11's alias-declarations with the "using" keyword.) There are nontrivial bits here, like typedeffing function pointers.

      AceHack> and as much as possible about the Preprocessor if that's considered part of the core c++.

      It is, although the preprocessor is really a primitive text-manipulating language that's applied before C++ itself is compiled.

      Chris> What I love about C++ is its complexity and that some operations in the language are undefined.

      Of course, C++ doesn't go out of its way to be complicated. Most of the complexity is there for a reason - usually to support tricky code, sometimes to support backwards compatibility (as obnoxious as it may be, C++'s compatibility with C remains a strength).

      As for undefined behavior, that usually exists because something is difficult to detect, and leaving it undefined permits significant optimizations.

      Ivan> I barely managed to watch this episode, but not because STL is bad but because I really dont care that much about language rules

      Heh. Remember, I'm not really interested in the Core Language as an end in itself. It's just that because it underlies all programming, and as a library developer I deal with very tricky code for a living, having a thorough understanding of Core is invaluable. It lets me write code with a complete understanding of how it's going to behave (users can do lots of things with the Standard Library and we have to be prepared for the crazy stuff they're going to inflict on us). Understanding the Core Language also makes it a lot easier to understand compiler warnings and errors. That speeds up my development cycle, and having no fear allows me to use complicated constructs more extensively. (Some programmers, fearing template errors, avoid templates when they would be a superior solution that would allow them to write cleaner code.)

      Ivan> 1. Regarding episode 2 dont forgett to mention pointer paradox.

      I haven't heard of that - perhaps I know it by another name.

      Ivan> 2. Do you know why there arent trie_(multi)set and trie_(multi)map in boost or std? To obscure?

      The Boost Graph Library could probably be used to construct tries. Both Boost and the Standard are developed by volunteers, so they consist of things that someone has had the time and motivation to develop/specify.

      (I got started with C++ by implementing suffix trees, which are a special case of tries.)

      Ivan> 3. One of the cool lectures (using TMP) would be solving this problem (if possible) : http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Dr-Graham-Hutton-Functional-Programming-Fundamentals-Chapter-11-of-13 with TMP

      Interesting - I will see if I can find some time to play around with it (which is how I did my Nurikabe episodes). http://www.cs.nott.ac.uk/~gmh/countdown.pdf formally specifies the problem.

      Ivan> 5. Idioms are a cool topic imho. Like I said I dont care that much about lang rules, but I like learning idiomatic way of programming in language X.

      I'll definitely cover the Non-Virtual Interface idiom.

      dot_tom> I've been using this language for almost 18 years and Stephan clear up some of the name resolution stuff for me in this video.

      Sweet!

      Guest> I actually have one question when you std::cout something in c++ why don't you include just iostream and you include ostream too I think iosteam will provide the ostream functions and objects too.

      This is actually an interesting story. In C++98/03, <iostream> provides cout but not endl, which lives in <ostream>. I followed those rules strictly. In C++11, <iostream> is now required to include (or behave as if it includes) <ostream>. I actually just learned this at BoostCon/C++Now! 2012, and one of my todos when I get back to Redmond is to check whether we've implemented this in VC11.

    • Mathias Creutz

      Thanks for the video, I am looking forward to the rest of them!

      As for typename vs class, I just stumbled upon this a few weeks ago =>
      http://blogs.msdn.com/b/slippman/archive/2004/08/11/212768.aspx

    • Ivan

      @STL
      Tnx for the answers... Regarding trie also I guess it is tricky to define what would be a "charachter" for for example int->MyClass map. 8 Bits of the int, Decimal digits of the int... ?
      Ivan> 1. Regarding episode 2 dont forgett to mention pointer paradox.

      I haven't heard of that - perhaps I know it by another name.


      If I remember it correctly :
      whoAmI(const T& )
      {
      std::cout << "Im a reference" << std::endl;
      }
      template <typename T>
      void whoAmI(const T* )
      {
      std::cout << "Im a ptr" << std::endl;
      }
      int *p;
      whoAmI(p);

    • Name

      Hey STL! Nice video as always. Detailed explanations of strict aliasing and alignment would be very appreciated for future episodes. :)

    • ArmandoMeabe

      Hello Smiley I don't really understand the "More episodes in this show" div... if I can't see any next chapter of this, means that there are not ready yet, right? There are other interesting videos but...

      Btw thanks Stephan yo actually answer your emails! You're great, thanks.

    • Ivan

      @ArmandoMeabe
      -"this show" is Going Deep, it includes a lot of stuff but this is the first and so far only episode of Core C++ :)

    • Chris

      Stephan, this question is not related to the lecture, but I hope you can answer it.

      When you ask for the size of STL containers, do you store it in std::container<T>::size_type or std::size_t? The standard says that for some containers size_type == size_t and for others it's implementation defined.

    • Vish

      Great job with the video. Can't wait for the next ones. Are they gonna be released on a schedule?

      Thank you,
      Vish

    • Name

      @Chris
      Just use std::size_t. It'll be sufficient for all size_types. However, with C++11, why not just using auto? :)

    • Charles

      @Vish: Well, they'll be released on STL's schedule. which is rather full with shipping VC11 Smiley We'll try to get these out as often as possible. We'll have the studio ready for STL when the windows open, for sure.

      C

    • STL

      Ivan: When overloading foo(const T&) and foo(const T *), and calling foo() with int *, what happens is the sequence of steps that I described briefly in this Part 1. Template argument deduction runs, producing the signatures foo(int * const &) and foo(const int *). Then overload resolution runs. The first overload binds the reference parameter directly to the argument, so this is considered an identity conversion (i.e. the best, Exact Match). The second overload converts int * to const int *, which is a qualification conversion, but still considered an Exact Match. Finally, a tiebreaker is applied: the first overload's "identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence" (N3376 13.3.3.2 [over.ics.rank]/3) like the second overload's. Therefore the reference overload wins.

      It's subtle, but I don't think it's worthy of a name because I don't construct such overload sets. (Part of how I deal with the Core Language's complexity is knowing when and how to sidestep scenarios that will hurt my head.) Dispatching on properties of a type can be tricky, and I prefer to use techniques where I don't have to dig deeply into clause 13 in order to figure out what overload resolution will do. (Template argument deduction is fairly easy to follow, it's overload resolution's rules that can be intricate since it's trying to apply rigid rules in order to produce the fuzzy result of what a human would consider to be the "best" match.)

      I might actually use this example in Parts 2 and 3.

      Name> Detailed explanations of strict aliasing and alignment would be very appreciated for future episodes. Smiley

      Alignment might be enough to fill a whole episode. According to my understanding, VC's optimizer doesn't attempt to exploit C++'s strict aliasing rules (whereas GCC does), so I'm not sure what I could demonstrate there.

      ArmandoMeabe> Btw thanks Stephan yo actually answer your emails! You're great, thanks.

      I live to serve. :-> (When I'm not on vacation playing Diablo III.)

      Chris> When you ask for the size of STL containers, do you store it in std::container<T>::size_type or std::size_t?

      In my own code, size_t. I am comfortable with assuming that the Standard containers will behave sanely.

      In the STL, however, I would be paranoid and ask for size_type. That would deal with user-defined containers (or user-defined specializations of Standard containers) which may have weird size_types.

      Vish> Are they gonna be released on a schedule?

      Like Charles said - remember that I am a dual-use technology ( http://en.wikipedia.org/wiki/Dual-use_technology ) and as much as I'd like to film videos and write blog posts all day, working on the STL itself for as long as they'll let me check in stuff must be my highest priority. I've just returned from BoostCon/C++Now! 2012 and a week of vacation, so a bunch of work has accumulated in my absence. After I deal with that I should be able to find some time to film Part 2.

    • Ivan

      @ STL
      tnx for the answers
      Just recently stumbled onto the fact taht u were at boostcon, but github gives error when I try to get your presentation. :(
      I hope it was similar to your C9 regex lecture. :)
      @Charles,
      can you follow STL during future C++Now confs(ofc if he goes), and record his lecture?
      AFAIK MS is gold sponsor and usually Boostcon video Q is cr*p(sorry Boost people, but you know it is true :) )

    • STL

      Someone else reported that to me too - I've notified C++Now!'s organizer.

      In the meantime, here are the original slides on my SkyDrive: http://sdrv.ms/JuyqQG

      This is an update of my old TR1 slide deck: http://blogs.msdn.com/b/vcblog/archive/2008/02/22/tr1-slide-decks.aspx

    • Name

      @STL Thanks for the answer. Yes, I don't think the VS optimizer takes advantage of that rule, so it would indeed be a little bit hard to show the effects of. Still, I think this is a topic connected with very much confusion. I know for example 3 very experienced C++ programmers, and they all have a different view on 3.10/10. For example: What's with malloc() there? malloc() returns a pointer to void, which obviously has to be converted to be useful. So, if I convert it to pointer to int, store a value, than convert it to pointer to short and read the value - is that undefined or implementation defined?

    • ChrisL

      Ah STL, glad to see some new content! I like your videos quite a bit. Thanks for doing this for the community.

    • STL

      Name: According to my understanding, reinterpreting directly from int * to short * violates strict aliasing.  However, static_casting up to void *, then static_casting down to short *, is a "legitimate" way to view those bits as a short.  (Aside from trap representations, which I've never seen in practice.)

      ChrisL: You'll be happy to hear that I filmed Part 2 yesterday! :->

    • Ivan

      For impatient STL is on YT:
      http://www.youtube.com/watch?v=mUZL-PRWMeg
      He also makes appearance giving comments in :
      http://www.youtube.com/watch?v=43ej-H8yHWE

      BTW quality is horrible, so I suggest getting slides and scroll them while watching videos. And again I use this opportunity to beg Charles to go go Boostcon and record at least MS employee presentation. There is a nice one about VS2012, but sound is bad. :(

    • Alan Dox

      This is simply amazing.


      I never realized how hard the intellisense and the compiler has to work to resolve the names.

      Looking forward to more esoteric topics to improve my programming.

    • MaheshV

      For some reason, I too smile when you smile. Awesome presentation.

    • STL
    • Gary Sanders

      So by using the rules of ADL it is possible to write code that is shorter and more concise, perhaps.

      Consider the following examples using the boost::filesystem lib.

      // a) use fully qualified names
      boost::filesystem::path p = L"c:\";
      if (boost::filesystem::exists(p))
      {
      }

      // b) use ADL
      boost::filesystem::path p = L"c:\";
      if (exists(p))
      {
      }

      Both examples compile, but b looks (to me) like an easier code snippet to understand. Are there any pitfalls of using example b? Would one form be preferred over another or is just a matter of style?

      Thanks again for another great tutorial.

    • STL

      (I noticed this by chance; usually I don't look at Part N's comments after Part N+1 is out.)

      In this case, relying on ADL is fine. Usually I rely on using-directives or using-declarations for even greater convenience, though. (You can't put them at global scope in headers, because that would be enormously polluting, but they can be function-local in headers.)

    • Isaac

      Thank you! This is great stuff.

    • Alfred

      FYI. Koenig did not invent ADL. He himself has said that:
      http://www.drdobbs.com/cpp/a-personal-note-about-argument-dependent/232901443

    • NayeemKhan

      Hi

      I am unable to download this video completely. It always gets struck at 99%

      I will try one more time using different down loader software.

      Thanks

       

       

    • CosmaCosmin

      you do not need a downloader for that,

      just follow the download posted instructions using 'Right-Click' and then 'Save As'

    • CosmaCosmin

      Thanks STL!

      Your presentation skills and knowledge(of course Smiley are impressive.

    • Ville Voutilainen

      You apparently do template specialization in a different namespace than the namespace of the primary template. It seems msvc10 accepts that, but it's actually
      ill-formed, so you have a compiler bug there. ;)

    • ronnie

      Stephan, great stuff. Very informative. Keep doing the good job!

    • Chetan ​Chandrashek​ar

      Stephan , you are my greatest inspiration till date . You are indeed an abundance of knowledge . Thank you for sharing your knowledge. Yes true that you are STL !

    • Sqandr

      I'm with example from 3.4.1 Unqualified name lookup, using VS2012-update2.

      typedef int f; 
      namespace N 
      { 
        struct A 
        {
          friend void f( A & );
          operator int();
          void g( A a ) { int i = f( a ); } 
          // f is the typedef, not the friend function: equivalent to int(a)
        };
      }

      Compiler complains that [friend] function f() returns a void that cannot be assigned to int.  Thoughts?

      Thank you Mr. STL!

    • Deepak Pant

      Thanks you very much for a wonderful series. I am putting through the excepts/snipped in git so that it is easy to browse and understand.

    • Vladimir

      Am I the only one who can not watch this video and get only HTTP 500 instead any of download options?

    Comments closed

    Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.