CppCon 2015: Andrei Alexandrescu “Declarative Control Flow"

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

C++omedian

Andrei is hilarious, but really?

Fantastic talk, though.

👍︎︎ 11 👤︎︎ u/slavik262 📅︎︎ Oct 19 2015 🗫︎ replies

The ODR 'violation' brought up in the Q&A doesn't matter because the only difference is a variable name, which any sane compiler ignores. They should just add an exemption for local variable names to make it technically obey the standard.

👍︎︎ 11 👤︎︎ u/augmentedtree 📅︎︎ Oct 19 2015 🗫︎ replies

@11:56: "Baby seals are dying... I mean human babies who are supposed to be Marines when they grow up!"

👍︎︎ 17 👤︎︎ u/o-genki-desu-ka 📅︎︎ Oct 19 2015 🗫︎ replies

Well, that was hilarious.

👍︎︎ 5 👤︎︎ u/p0nce 📅︎︎ Oct 19 2015 🗫︎ replies

At the start he asks if (someone) and Chandler are there. I take it he means Chandler Carruth but who was the other name? Sounded like STL but googling C++ STL for a person's initials isn't going to help.

👍︎︎ 3 👤︎︎ u/krenzalore 📅︎︎ Oct 19 2015 🗫︎ replies

The C++omedian

Can we please stop?

👍︎︎ 8 👤︎︎ u/not_american_ffs 📅︎︎ Oct 19 2015 🗫︎ replies

c++ question for @12:20, why is it a bug to have copy_file_transac inside move_file_transact's try block?

👍︎︎ 2 👤︎︎ u/Kache 📅︎︎ Oct 20 2015 🗫︎ replies
Captions
it's a great honor to speak again at CVV Khan is my second time after last year I'm already seeing a few familiar face it's a great honor but also you gotta imagine it's a great responsibility as well and there's how many people in this room 200 I know 400 no that would be so let's say 200 people and you're the best right I mean you're the best folks at your respective organizations it's like your employer went like Oh Johnson is not doing his job he's drinking all the time order his desk not writing one of code let's say into a conference no you're the best now you know is they still here because he says he's gonna be here STL all right see Chandler there's a channel is here a measure I play something like Inception and Chandler I planned a really bad idea in his mind he goes down and kind of spreads I mean here's the thing if I give you a bad day today the stronger folks in here I give you all a bad idea right now I just could have consequence on the history of humankind I could rip a real bad right I could go like pretty consequential so you know I mean pictured this image like in 1960 does this guy at the conference you said you know that is the global variable and it was good and then think of that right it was man I don't want to be that guy so it's a great responsibility to anyhow by means of introduction now this of course doesn't work huh it works better if it's turned on right give me a second here I like the most advanced programs in the world here engineers and all that stuff and what it does have a battery anyhow well I guess I'll go to school and you know by means of introduction here there is the introduction slide because you know in my academic career I've been always being taught that a good talk goes like you tell them what you're gonna tell them then you tell them and then you tell them what you told them and that was the standard I'm not kidding that was a standard structure of a talk but then I read this the secrets the presentation secrets of Steve Jobs it was like what I white white Steve Jobs never has an introduction slide never and indeed I looked on the YouTube has no introduction slide so they said start with a story open with a story give a give a story from your heart from your soul that this and that's true and connects you to the audience let me tell you something has really connect me to you to be very honest like I don't want to be here and we qualify let me qualify that I never want to be in the first like 45 minutes of any of my talks ever I hate it it's really bad like the first lay the first minutes are really bad because it's all it was it goes like this so pictures are saying oh would you come next year at the conference sure it's six months from now no problem and then you know the months go by and the date approaches and you have no slides and then your does this pain compression which is we like in the last hour on the plane after it landed there's an immense play there's a direct funk funk tional of productivity they're right there like it's amazing it goes to infinity productivity I get most of my slides done and literally I've had talks in which I finished my slice leisure like two minutes before giving before sing this is my slide right and I had the organizer like behind me and saying you know Andre maybe I should announce that this is not going to happen there's never been a talk I've ever given that I didn't want to wiggle myself out of I've there's always been a thought I've never like done it that you know good work ethics what-have-you like you know mom told me well all that good stuff right but it has always been the thought if I just could wiggle up I could be sick happens you know airplanes you know delays whatnot so well and then this one's going to happen like this talk this talk we're going to go like this we're going to move on in 30 minutes into the talk I'm going to have one of those what they call them extracorporeal experiences ESP ESP right per se experiences so I'm gonna see myself from like up there talking and you're listening if you're not leaving right and I'm Varrick but this is working I they didn't leave this is awesome right by the way who's like who's been who is for whom this is my first talk life Jesus okay so I've talked to John I have bad news for you I thought the junk out they don't give refunds so take it easy okay so that was my story form as did we connect here do we have all right so let's start with practicalities I challenge you to write the transactional file copy function let's write the file for country that you know fault hey John something that either succeeds or fails successfully right it all is either copies the whole file or it doesn't copy anything right so I don't know what I don't want is a fraction of the file on the destination drive make sense again like when I was doing research the worst thing that could have happened was to have a file of data which was like you know I don't know Wow 800 megabytes and then you copied and for whatever reason you copy like see how megabytes of it and the data at the end would influence your results would be like between success and failure it did happen so this is awful right so we want to define a transactional file copy function either copy the whole file or if you don't succeed you don't want them you don't have kind of a fragment of a folder great I also give you a cheat sheet boost has a great function which is called copy file that should be useful right all right so we have copy file which has the spare thing which is like a string but just you know smaller and this is what I got so far oh well first I'm going to copy into a temporary file called the original file name plus dot delete me which is very indicative which is like you know if you see deleted right if you ever do LS in your directory and see they're going to delete it because it says so right it begs for deletion great so beef is not by boyfriend's booze five system right but I didn't have room on the right beefy path so I'm going to create two dot native the string I pen delete me and that I'm going to copy into the temporary file with boost and I'm going to again use boost to rename the file from temporary to the final destination but the key thing here is what if that does either of those operations doesn't succeed and in that case I want to remove the temporary the delete me file I want to leave some garbage in there right sensible right great well notice that I'm using like the remove I'm using the global on the POSIX why do you think so it doesn't throw so I want to kind of do a best-effort thing to clean after myself right it's I don't have throw if he doesn't succeed because that's a disaster right so great I'm you know catching everything and throwing it you look at this function you have if you like me critical you'll see that it has like what eight lines how many of these lines do work about three right there's the copy does the RAM does it remove and everything else is sort of moist so I'm not happy about it you know what I don't like it so well we have control flow at try and catch you know stuff going on and you know although the stuff is not dedicated to what I want to do is just why do I throw it's like you're right baseball and they throwing catch balls around and stuff but it's not about the ball it's about how they wear the hat while doing it it does it's not the ball that's the subject here right so why am I talking about catching and throwing things actually this kind of if you take it I could take offense at this alright catching everything like there's a dot dot dot like you know what I don't care I'm catching with everything there is and you know what I'm throwing everything there is it's not even fair right to from a moral stain standpoint right and I shouldn't visual studio a while ago at least it was kind of not nice to do so is that still a case a steel horse yeah you know that kind of stuff you see and even he said that inception right the inception here alright so I don't like this great well let's move a bit forward with composition I'm marching forward so I want to now define a transaction file move function which other moves the file entirely or does move it oh by the way let me amend what I just said here there is a one key point that's kind of lost in the translation here did you know that rename is atomic this kind of an important tidbit is there right in poses like you know rename is atomic on the file system it I did either rename store dozen but doesn't kind of stop somewhere in the middle this is important right good with that in mind let's move to the far rename thing so well here's what I come up with alright it looks about the same except I'm going to reuse my copy file transactions I'm going to copy the file and then current remove the source and if things fail I'm going to remove the destination there's some that something doesn't sound right there like I try to copy this file for whatever reason I didn't succeed for example it was read-only or you know maybe the source was impossible to read because of a failure of some kind and therefore I'm going to you know what I'm going to remove the destination whatever the hell was in there that doesn't sound like a nice thing right you see the bug how do you fix it how do you fix it come on fix it for me fix files are disappearing right now things are baby seals are dying and baby seals I mean babies like human babies who are supposed to be Marines when they grow up it's not okay it's that bad okay so help me uh-huh yes then no move that one way I move the trying down one line thank you I was thinking the other way around so I'm going to copy the file in transactionally first and only after that works I'm going to ask myself the philosophical question what I want to remove the destination ever right good awesome this is good as far as I can tell baby seals are alive and safe and still I'm not just as unhappy as I was because I might think of this this is a kind of trivial examples they fit on a slide either if I care to make the font smaller and you can see them from the back right so but you know in real life things can get hairy pretty quickly yeah like five operations to do and you have like all of these tries and catches some sometimes embedded one within the other and what if I didn't have this removed game post six I had to put a try-catch inside a try-catch etc right so things are not they don't look well I don't like the way they look so what do we have for improving the situation here friends well we have our ai ai which doesn't quite help because all right I like execute that destructor no matter what it doesn't executor destructor conditionally if things didn't go well then let me destroy a primal deluge right etc so it's not like that right so scope guard is the same it's like an ad hoc destructor and when you compose things as I said it only makes things worse so that's not I you know it doesn't seem like it's leading us somewhere meantime CPP core standards very nice yeah you know you shouldn't write too many try catch so not good for you not good well aha if they're not good for ey they have been great them why do you have me write catch everything and then throw it again as long as you do it in style right I don't want to do that so but I so I think that a curb wrote that right and he's with me in spirit here although he's got a bad cold so anywho so there's something that I don't like here and when you start liking bad idioms when it's not liking go to you know something's wrong in the kitchen right it's it's clearly clearly we have a problem here so okay here's my conclusion I like to generalize so I say explicit control flow is fail and whatever right great do you agree with me okay I'm a very good salesman all right so now let's get a unit-less turned out let's kind of think about something else for a minute here think about like the declarative programming and the tenets of what declarative program is there's all the sign there's there's a life you kind of google for it you're gonna see that there's a very nice talk about like oh you state the objectives of what you're trying to do and you're your you know your world peace I want world peace and the program is gonna write itself right that kind of stuff but more concretely there's a bunch of declarative code you write and use on a daily basis give me examples sequel make files regex ten templates that's a heavy one that's heavy dark what else make right I said it right so there's this a bunch of there's a bunch of code that we use on a daily basis that's highly specialized and has this declarative mold to it in which you specify the final objectives and the mechanics of achieving them are somewhat automatic and that's pretty awesome so I kind of like that idea and here's like here's what I had like you know I would jump in the bathtub and I said Eureka REI I destructors are declarative because you write them but you don't call them you say well whenever the subject goes away here's the obituary right here's what's going to happen when the guy dies right interesting you never call it I mean you can't call it you know how to pull it right I told you the best you're the best you know how to call the destruct if you so wanted right so but you usually don't call it right Johnson doesn't call it the guy who drinks under his desk right is this not pulling it okay so okay interesting so I write you states what's going to happen and it happens automatic semi-automatic let's say right that's very interesting so let's kind of take that to the 11 and extend the same consideration for scope guard if you search for like scope guard or scope eggs if you cannot find like my previous work from like you also go it I think it was like the nineties I think it was maybe it was at 2000 but early right or so much so much younger and so much more you know idealistic and everything and we weren't married most of us didn't have kids to worry about so those are the days of scope guard okay awesome great so you you know there's a macroscopic seed which I'm going to give a few details about and here's how it went let's look at the macro so there's a scope exit and I'm going to I took this the statement from our youth to the 2015 because I have this thing at the end of the macro so first of all let's start from the end of this macro what does this guy do huh it doesn't create the lander that does nothing he creates the fragment of a land that that does nothing right it's worse than that right so this kind of starts a land a capture everything by reference start the land and what you need here is the open curly brace and with the macro you have a pseudo statement because all of a sudden is Right Scoop eggs the open curly brace to write code and that code is going to be automatically done when exit the scope what do you know interesting well and kind of the trickery the trigger rule that I'm doing here is I define that the enum class at the top scope guard on exit why did I define it for just I have a type I'm literally this is why I define it so there is a type it could have been instructed believe anything enum class just was at the fingertips there it is nice because like mostly blue two things blue next to each other look great right so then I define a small temporary that takes a lambda and adds operator plus of that guy in on classes for garden exit and any lambda it's going to just give me the lemma and then scope X it is going to create an anonymous variable to which I'm going to get in a minute which is going to be d cos cop garden exit plus the beginning of the lambda this plus is going to invoke that guy and all of a sudden I have the creation of an object that's anonymous how do you create an anonymous name for an object in C++ who knows I'm sure some of you know create an anonymous name object and your name is C++ alright so I'm glad I have the slide because no matter what I talk about I could talk about like rocket surgery okay anything and at the end of the talk there's a guy who comes to me and says you know that macro thing how did you do it I was kind of cool I could use that the templates whatever you know awesomeness you know just and that macro thing I want to know all about it I want to know how it works man I can use that all right here's how it works so there's a counter thing which all compilers define and it kind of increments itself every time you use it but not quite I'll give you a in a minute why yeah because you don't increment it twice in the same use because otherwise this wouldn't work so it's designed to make this work so there's an indirection here so there's an animus variable of string and it's going to call concatenated string encounter and concave a is just going to simply put the user to hash preprocessor thing why does why is why do I do that in Direction via concatenate who knows yes otherwise there's like seven stages of doing this crap right I'm not kidding like pre process is like the most complicated thing in the world right and among this complication there's the fact that if you don't do this in direction with concatenate and you're using straight the hash hash operator it's going to concatenate the actual symbol I'm just going to counter on the screen underscore and that's one notch what do we want the expand that guy first and then concatenate that guy so what you're going to get fused whenever right whatever STR the string is going to be h TR 1 4 3 5 and next time you use it is going to be like 1 3 4 6 and so on right so there's a different variable every time different identifiers every time getting back to this guy this anonymous variable is going to be called scope exit state follow the immediately by some number and every time you use it is going to be a different number okay so please don't come to me after this talk and ask me how this is done like I know pretty much I told you everything I know okay this is where my knowledge of preprocessor ends and wants to end okay this is where I'm happy great anywho the users doesn't look nice that's the sort of the upside of this because I can open files in scope exit I'm gonna close files I can allocate memory with malloc and let's go fix it I'm gonna you know freedom and everything and you know by the way don't forget to put like a semicolon after the pseudo statement there because otherwise it's gonna you can have one of those like very long error messages that we all learn to love right okay so this kind of hold stuff so I don't want to dwell on the old stuff for too long right great now this is kind of getting almost where I want it to be a row laundry we want it to be is to have the option to run some code whenever a scope is exited but remember the examples we gave it's not whenever a scope ends but it's only when the scope is exited by an exception so I just want to do some code when the scope is failing meaning either the scope in good health I can do me I like 100% health right and when you exited you're like completely messed up like the monsters gotcha right so skull fail is going to execute code whenever that is respawn right that the scope fail is the code for respawning you don't play much Doom do you okay my jokes were about like internal references don't work but I want I want exit and I want fail and by the way since we're here there's a sense of symmetry in all this because I want to execute code no matter what happens when the scope is done I want to execute code whenever the scope fails and you know what I may want to execute code in a celebratory way whenever the code exits nicely whenever the scope does not end with an exception make sense so I'm these three guys on these three pseudo statements exit fail and success right and actually protein production code if you if you look through it you're going to find a lot of uses for all of them but mostly for these two guys this is more rare it's it's you it has uses I'm going to give more details all right so let me kind of emphasize the fact that here we're talking like it's something the clarity because I'm stating again whenever the scope is like in we're like basic on our resume next it's awful but is declarative right remember like on arrow good you know never like do something print a statement you know there's an error and resume next right so this is declarative is nice because it saves us mechanics it's it's expressing goals I've good news for you so this like how my slides evolved literally so first it was like may become portable in the future and there's like a smaller number here the proposal and you know as and you know I gave this talk like three times for once with just my mom but you know three times okay so first time it was like with me and you know I wish I have a dream right ii was like wow there's a proposal herb worked on it right and today i'm very happy to announce that it's done it's a done deal it's amazing that it's a done deal because all i had to do was write the slides which I hate give the talk have herb listen and take a vacation you took care of it which Rio so alright so c-plus was 17 has it and here's how they did it they went with a principle that's like from the Egyptians like when in doubt replace bull with int right think of it I bullies bad right like vector bull need i say more like good is awful right terrible huh that was a cheap shot I agree alright so you know so they raise bull with ink and they replace like singer with plural and there's two effects of this we have a new function which is in uncaught exceptions and the second effect is that Google hates that because with Google like plural and cigarette are the same thing so if you search for one you're going to find the other so it's kind of messed up right now but Google is going to figure it out right so you can search for it I'm going to find like a million results for it on code exceptions exception and then you're going to find how did you girls girls did you mean the singular there you know so so um you see what I did there like this is a the comment it's like the beginning of a rap song right they're like you know someone I don't know well what does this do could someone tell us yes please the number of exceptions in play but how come I how is it possible EPC process to have several exceptions flying someone else how is it possible yes an assertion thrown in a nested catch the execution of the catch itself does not mean the exception has been accounted for yet and this was a classic failure scenario of the singular version of the function the one that returned like the awful bull right so it was bad it's essentially a curb had a full like item in his book about how that's useless that you know the singular function is useless and all kinds of bad the body because it's almost like it's working it's just not right so if you try something a throws and you catch you catch it and then you try something else inside the catch and he throws again you don't know what the hell were doing anymore right so this is where we are and unquote exception is going to increment that counter whenever a new exception is thrown right question for you can I leave a scope with a smaller exception countdown when I entered so I enter scope execute some code and then when the scope is left can the unquote exception can't be smaller yes if there's a bug in the compiler yes right the scope the scope should be like a scope that doesn't throw it's going to conserve the number exceptions there right there's nothing that can be erased inside the scope you can kind of enter a different scope and etc right or you can exit a scope but within the given scope you can that number can't go down can you go up oh yeah right by how much by one so enter scope and when you exit it it just can throw one exception right from that particular scope right okay but then when you enter nested scope you can have like larger numbers of this exception count right can it be negative I hope not yeah it could be if there's a bug in the compiler right okay great by the way they didn't make it on sign because I'll come on unsigned like I see if you're the best so tell that to Johnson okay all right explain you tried last weekend didn't work out he was drinking too heavily okay great so well let's use this guy and this is like essentially like the way that I think is supposed to be used I advocated for it by using this example and this is like essentially this is the only known use of that function I'm not kidding there's no other use that's meaningful alright so let's see hmm first of all like notice that this like no except is blue so I updated my logic to account for C++ 11 and beyond right so uncaught exception counter I have a little class that all it does it counts how many exceptions are in the scope of it and leaving the scope of it so we initialize the when you initialize by default this this guy is going to save the exception count by calling uncaught exceptions and it has a method that tells me now do our are you throwing and wicks is a new exception leaving the scope of this class so this is sort of the basic the basic wrapper around the down quote exception that is useful I want to save it when I enter my scope and I want to consult it when I'm leaving the scope and that's all I want to do okay great so far so good okay so now let's kind of I'm giving the talk there should be some template somewhere so it's inevitable so let's see well we have a template that takes a lambda and a boolean that tells me whether or not I want to execute is an exception remember we talked about scope success and scope fail is hopefully the next section I want to throw a scope success I don't want to throw so that's that boolean I want to reuse the code across the two so then we have we keep the lambda and we could we keep the on code exception counter which edge we just defined as the slide before we initialize the font the land that all that move stuff and you know what's interesting is this the destructor when the destructor gets executed and look at the counter did the scope generate a new exception and if that is exactly what I want I'm going to call the lambda otherwise I'm not going to so if this guy's so this like execute exception is like a constant boolean right and if I do want to execute an exception this guy is going to be true and if true equals the new exception is being jarred I'm going to call the land otherwise I want so I'm going to reuse this class for a function and for success in failure by the way you notice like the nice conditional use of no except like no except like takes a boolean right okay let's let's talk let's dwell on this guy for 30 seconds because it's well worth it if a function fails if I'm throwing an exception and then I want to throw like while the exception is flying I want to execute something that's also throw an exception what's going to happen huh a CD terminate sudden-death right so you know in that I mean that's kind of bad I mean I don't care it's terminate so I may as well claim that the lambda is no accept so I'm gonna write that that's a no accept you see what you see what I'm saying if a guy wants to go kamikaze was the purpose in giving them a helmet right because a helmet would be like there's no no except it could throw conceptually it's his right to throwing exception but in this case is I if this guy wants to go I'm not gonna waste a helmet on that guy right just save it keep it that's no acceptor remember whenever I see that no accept helmet okay great but if I don't want to exhibit an exception so if I want to exist on success I may as well generate an exception there's no harm in doing so because the scope is about to exit with success and there may be a guy who doesn't like success fear of success like v fear in the United States right like amazing I would be afraid of success right he turns out there like right but you know and this is it great does it make sense so far are you getting bored here okay well I'm getting there but I gotta keep on doing this right so they're not like the 30 minute into the talking like oh there didn't leave yet all right so this icing on the cake I'm going to define a new macro let me see if I have the macro here yeah there it is so remember like in Ian's class and I'm going to do the same for the scope guard on fail so I define a new type I'm doing the land I'm doing the operator plus I'm doing the you know there's a DK in there because it didn't use Colgate right and that kind of stuff and I've operator plus that's going to help me define this macro so scope fail skull fail introduces anonymous variable that anonymous variable is the you know it's that object constructed plus the beam over lambda and by the way I put the helmet there right the lack of a helmet right now except because if I fail again I may as well say it's no except you're not entitled to throw from us and that fails and actually care about it you can't throw you can't come to me about it I can't blame you all Andres is that no except I thought you're a good guy right I am a good guy and not give you a helmet all right make sense all righty then so let's see what the aftermath is here that's a long time here okay great transactional copy create a temporary file name should anything go bad declarative right should anything go bad remove the temporary copy the file and rename the destination and this time every line in the function is meaningful it does work it gets work done it's interesting there's not throwing and catching and you know there's just I'm stating what should happen uncommon should anything bad happen let me delete the temporary created and that's totally fine right so do you agree that this is better than what we had before it may as well not but I mean but I got the microphone so who cares okay awesome transaction move you know here like what's interesting is that the sequence of operations matters remember like we had that try and depending on where you put a try and the scoping of things all that control flow was meaning because gonna be important but in a mechanical way here all I need to do is kind of order the operations appropriately and we're done like first I'm going to first thing I'm going to do a transactional move by the way so this assumes you're not on the same file system because our asses are cheaper so remember I have an extra restriction all of my code has to enter fit in one slide I'm not kidding so all I write it's got to be simple enough so it fits on a slide because otherwise of course the question is like what if from and two are equal what if they're in the same file system wider if your copy like an idiot something else in the same directory let's set yourself this I assume our kind of elsewhere right so I'm focusing on the core matter here but don't I mean don't think I'm an idiot although I mean you could because I might but you know at least of this I'm aware of can you put it that way so okay we have boost our season cup sorry that's not both the copy/paste error that's not in boost policy file system copy file transact I wrote it in the slide before this right so copy file transact from two so first am I'm doing I make sure that I have a copy of the file this is like the fundamental thing I want to do here as the first step and regardless I want to get that done and the Deb guy throws that fine and second I'm going to put a stake in the ground saying well if what follows fails I want to make sure that I'm removing the destination right and then I'm going to remove the source so and actually this is not going to simply thing if you have like if and else and stuff like if you write it in C it's actually more complicated on this which is pretty interesting because everybody things like that's the easiest way but declare declarative is is easier than the easiest way because if you just say what should happen and it's all flat and nice right awesome let's see well this is kind of a reiteration of the helmet argument yes oh my god whenever I hear that doesn't bode well yes the scope failed if I if I move it before right you remove the distinction like kind of compulsive and wrongly you shouldn't right so yeah it does matter where you put it so and the sequence does matter and that that's a good thing because you can achieve several things sorry copy file is transact transactions so if that guy throws I don't care I don't need to do anything because it kind of took care of itself in its own way right so that's great all right so let's see what about three right now we have scope success we have scope fail and we have scope exit so scope success I said you know if the scope is left with success this guy could initiate an exception it's there right because no exception has been initiated yet so it does not terminate all that bad business right arm scope fail can should not throw an exception that would be the Kamikaze thing to do save the helmet put no except in the document it assumed that guy's not never gonna throw an exception because that would be really bad right scope exit should could it throwers could not sometimes so scope exit like a destruct it's invoked whenever whenever the scope is left is going to be executed right so the fact whether it throws or not is statically indeterminate so go conservative vote conservative right so you go you say I don't know whether this guy's going to throw now dynamically so what I can say that statically I can't tell so I'm going to assume the worst right great so only this guy may throw and you may want to reflect that in the respective signatures so here are a few examples from entry from different production code that I've seen and they're great I like I like them so wanted like post-conditions string trained well on success I'm going to make sure that the converting the integer back to string is is good right it gives me the same string right so post condition very far and notice that it only does it on what the scope is exit with success if it does a failure you wouldn't execute very concise changing of the guard well this is a bit low level but really this like the fastest way of lexing anything you're on alexis tree if you're on a legs code this like the there's no faster way except if you go assembler right and the way it go is you take the point of the buffer you have the size there and what you do is you replace the last character in the buffer with a known terminator like in this case 255 and then you write a big switch you know for every character you kind of do a big switch and inside that switch you have a case 255 which means I reach the end of the buffer what is the speed advantage of this code as opposed to kind of a for a non infinite for for until you know for I equals 0 to learn I'm going to do something with the current character what is the advantage who can tell yes that left oh sorry yeah there's no choice yeah but there is anything they said the switch right so that I'm making the choice still yes the switch is a table lookup I would generalize that and if you don't know whether it's a table lookup or not or not but you do know the following but essentially like switch is optimized for I'm going to choose one of many things and often it does turn out to be a table but you know some other times it's like you know zero for jumps or whatnot right but what I know from this is that most of more often than not the code is optimized for so if the cost of each one choice in the switch is divided by the number of total choices I will switch 100 branches I could think the cost of testing one guy out of these 100 is somehow a fraction of the cost of testing each am I making sense in the table thing this is obvious the table approach it's a wove one lookup right and the cost of testing for anything is the same and small right whereas if you put on if at the top if you put like a loop at the top you're going to test that guy first and then you're going to do a switch save like to test going on I have one inside the switch and I have one extra one telling me whether or not I got to the end this is like 5x I'm not kidding this could be like if you write a simple lecture even for C++ itself if you write a simple lecture this could make a huge difference but of course I want to preserve the last character because I did not this guy here at the end of the loop what if it was a different character that was meaningful to the program right and I want to help that guy separately it's no performance cost to me because it's the last one it's I'm doing that work once right but the nice thing is that here we scope raise it I get to kind of save the put a character back in the buffer automatically make sense all right by the way there is a kind of a bit of dirt in this there's no the buffer is not Const so even I'm supposed to just look at it no I put up cons there I put after a pointer just to mess with y'all right so yeah let me put that concert see what they say and nobody said anything so right so yes when do you process the character at your temporary overall at the end of the switch statement it's a one-time work and you know what in there often you find yourself using a go-to and you could go to inside that for somewhere right it's kind of weird so I'm not I'm not above using go-to right all right scope change this is again from production code there's a global boolean that tells me whether I'm sweeping them doing something or not clean up and I'm setting true whenever the scope is exited by any means I'm going to set sweeping to false and then I'm going to do stuff how could I do this with a destructor yeah so you kind of create a little object with a boolean inside and it has a constructor and destructor and I call it like I know sleep guys sleep sweeper right and it's a single time probably and it needs to be visited right and the bullies not good so you want an into there and you know it becomes like a project right so you don't want that you want to create a new type just for this thing so you just use copics it and you're done right great all right ah this is again from production code there's I had to call F lock lock and unlock things and there's no type there's no it's this boost has nothing for it right so you're looking boosting nothing so how do you use it all dice have to sit down and write on your type no I don't have to because in two lines I'm done right let's go pigs it very easy of course if you want to do systematically I would I see to make this on abstraction say file lock and make it an object and write the r-value constructors and all those good things right yeah I'm honestly one too if if you committed to it right okay so there's a there's a thing a thread going through this in which all examples I gave have some declarative bent to to them they're not that imperative because they specify goals and contingencies and actions they don't specify when the actions are going to busy they're going to just specify that these should be done should things happen should the scope be exited to the scope exe be an exception should we scope be exited via anyhow right so that's nice in production we note we notice that if you start to see scope you're not going to need try that much and catch and all of that baseball game right there's not much need for it anymore which is great the nicest thing that I like is that the flow becomes flat so you know if you're like me like code that sticks to the left side of the window right I'm not kidding so it's nice to have like low complexity that way because for example I think of this if you indent too much then you start fighting with your co-workers was the maximum Collins right and there goes a holy word like forever right instead you say you know what just you know stick your code to the left-hand side and you're gonna be fine and all is good so no more worse and the order of introducing things matters this is unlike certain declarative code by the way in a made file not always but this is make I mean it's not systematic right but in a make file it's not it's not supposed to be even like understood by humans I think but some often sometimes often it doesn't matter what order you put things in and make fun right except when it does but right and there's also like other declarative languages in which it really doesn't matter the order in which you specify things for example in a regex if you are like alternatives with the pipe it doesn't matter what or I put the alternatives in it's just the same thing right and so on so in an SQL if when you select things so it's well if you specify join it does matter cetera but by and large operations are not sequence dependent as much but in this case this is a bit more imperative it does matter what or they put things in right all right well so there's one detail left to to figure out like this is from the future like you know we come from the future when we say oh yeah it's see 117 but the year is 2015 and whatever are we doing for that minus 2 Delta here right here I have good news I seem like STL smileyriley and I'm seeing Chandler right kind of nodding there I hate this guy okay so the nice thing is that even before super of the 17 unquote exception had reached the first cosmic speed you know that you know the cosmic speeds and everything I would say in the process the first cosmic speed is thank you the first cosmic speed means there is a major corporation that implements and maintains this code this is a first cosmic speed if there's a guy who in his free time does it and takes care of it that's not off the ground it doesn't take us to space right he gets into the orbit once there's a major corporation kind of taking care of it and there is Facebook Facebook folly has had for a while actually in github it's had this folly library and inside the following folly library there is a scope garden header which contains whatever the hell it takes to do it on GCC Marshall give me a second here I get to you and I realize I mean this should be spelled Marshall khlo but Villa was the first time I found AHA okay great so at the end he should say for clang so here's the thing it's all Google's fault because whenever I search for the plural it gives me the the singular and I don't know who did what and when okay so I'm going to actually I'm serious I'm going to ask you to to intervene at a specific point so first of all first I heard there's this guy Afghani who actually wrote before it was done before it was even proposed he wrote this thing so he saw my talk and he wrote that library which does I'm magic to make it work on em SVC and on GCC and probably on clang because GCC and clang have a lot of similarities there a B is so so this guy kind of wrote it and kind of took care but it wasn't the first cosmic speed there's a guy right great but he wrote me mani he said you know I wrote this I'm taking of it and this is awesome so he's codes like a lot of cast a lot of magic constantly probably if you change of Y space is gonna go blow to hell right but it works great so then we took we took Afghani scald and we went I want I went to the Facebook folks and I said you know folks we got to do this because you look at these casts and this ugliness this is awesome because we've got to be on top of that right so okay so Daniel took it and kind of put in phalion since then Facebook maintains falling therefore maintains for guard so we're kind of there right we're spinning around the globe first cosmic speed second cosmic speed herb as I said all I had to do was to herb was hurt here's how the code looks should be and herb said well I'll make it happen and I'm really sorry if I offended you he's Canadian I realized I'm not speaking Canadian very well but I tried to okay so and then Michael whose last name I didn't get and he must be in this room here implemented for visual studio 2015 James James let's go to James I swear does a guy Michael next to her band my understanding of the exchange was that he did it but thanks James and James McNally's thank you very much 2015 it's it's in production it you have it if you use Windows right if you have it okay so you have uncaught exceptions you can you can take my slides and write the code and see it not work okay so we have it in Visual Studio we have it for GCC and Marshall this like the moment you kind of tell us what what's happened Clank three seven has it who knows the GCC story which version of GCC has it I couldn't figure out it's I mean there's a lot of discussion about it there's a lot of patches there's a lot of code it's done I'm not sure which version so what I did I was like you know I tried it in Ubuntu whatever the hell I have and they didn't work and I said well let me Google and Google then messed it up right so I don't know some GCC has it probably five - that's like after kind of looking through the everything and kind of like in matrix like looking through the you know blonde brunette whatever I saw it was five - was the answer because somebody said in a discussion oh it's going to come after five one so with my like magic powers there five - should be it right great awesomeness so I should like Marshall clothes name should be there because he wrote a bunch of code for clang that's your right okay so he's the author of the patch and everything and essentially what I'm saying here is like you have you have some non-standard stuff in Folly already done with scope guard it's everything is there the macros anonymous variable easy in there don't come and ask me it's there it's come do go look okay hunt do look for it so you have the amount standard thing with scope eggs and everything you have it in the standard bye Thank You herb very much and I'm sorry if I've offended you we like James did it for visuals of Visual Studio 2015 so it's already there even though there is not yet 2017 which is great all right any question before we summarize yes how do you deal with a placated with code that doesn't care about transactions so code could still conceptually fail but not by throwing an exception these are this design doesn't cover that so everything it does is predicated on notion that the exceptions are failure and lack of these sections are success so it doesn't apply yes scope exit can't throw cannot no sir it cannot throw well it depends how what you consider good and bad here understand this to the question sure okay I love this this becomes and they're always in the last row they're like the best questions come from the last row and by a guy who has like an accent as bad as mine and just I don't okay so loud microphone thank you let him we could throw our throat from scope exit before is that right we could throw from scope exit before why is decade why is it not okay anymore yes okay um it was not okay to throw from scope exit before no I'm not kidding so there's this article I'm I think I know what you're getting at this is article and I allowed like in my initial work and I was young and the money you do what you have to do right so I said you know at the end scope exit if you feel like if you can throw because it's possible that you know the scope is not actually exited by an exception so you could have a conditional in there that just so the code could be dynamically correct but in you know in this version when I grew and I became more wise and right or whatever older definitely right so now I'm saying you know what in scope is you gotta be conservative you don't want to take risks to anymore because you're not young any longer so my answer to your question is it was not okay for scope easy to throw before and it's not okay today thank you so yes okay aha if you have multiple scope exit clauses what's going to happen there no they're going to exit not out one after the other it's going to be your calls are going to be answered in the reverse order they've arrived which would be a weird policy for Comcast but I would love it right so your posts are going to be answered the other way around and more interestingly could have scope exit and scope success and scoff fail kind of there and they're going to interact weirdly because what if you have a scope success and he throws an error and then you have scope fail so you know what homework exercise for the attendee this is awesome yes counter is a part of is a compiler extension can it be made part of the the C+ or standard you know what I'll route Chandler or were you okay Chandler he's like what do i okay so okay so that means no I think it's like International Sign Language for no counter is a recipe for your violations counter is a recipe for OD are violations in one definition rules but not in this case not even not on my slides my friends okay let's make that clear so I think counter is like one of those things in which you use your stuff in an inline function do you use your stuff in an inline fungal you scoped card in an inline function why not ever well it's in the Constitution could you have an audio violation okay okay well you I told you no refunds sorry about the head alright there is one more caveat that is maybe more subtle landis which which goes like this you could have like an return that doesn't move from one from an l-value in the scope and if you have scoped AC depending on what's in the your scope it may find the value already moved from so actually there's a German we emailed me about it and he said well there's a problem here because he see process 90 that couldn't happen and I routed that to Howard Hinnant and he said oh that was actually possible NEC was 98 as well so it's an old problem so if you're like even if you have a destructor depends on what in the scope you it may find like data that has been already moved from so that's that's a known danger to some extent um any thing we have time for - one question last question I swear yes standing ah okay oh this is essentially what do you have any language but there is something is this what we have in the D language yes so these three are actually statements in D yes I hate macros is there any way to do it without macros is there any way to do it without macros well why macros are fun well so there's an idiom that's so scope guard can use conquer without a macro and you can use like minimum you know without all that operator plus nonsense right you can use things but you got to kind of give them names and people do like put an underscore there right for the name and there's like two you have like well you have to underscore I guess right three put on square one and stuff like that yes Chandler that does fix your er violation that does fix the OTR violation so maybe in lock and by the way under underlined doesn't have the same problem does it okay so I'm not everybody knots I self or not means no right great yes louder yeah so you got like two on the say but those shall not put two statements on the same line C++ for guidelines I mean come on it's in the book right awesome okay I'm loving this but we gotta summarize at some point here thanks very much you
Info
Channel: CppCon
Views: 81,797
Rating: 4.942616 out of 5
Keywords: Andrei Alexandrescu, Declarative Programming (Programming Language Paradigm), Programming Language (Software Genre), CppCon 2015, Computer Science (Field), Bash Films, Conference Video Recording, Event Video Recording, Video Conferencing, Video Services
Id: WjTrfoiB0MQ
Channel Id: undefined
Length: 67min 34sec (4054 seconds)
Published: Sun Oct 18 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.