Oli Scherer
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- tags: rust --- # `constexpr` vs `const fn` It has recently [been brought to my attention](https://twitter.com/InsanityBit/status/1206621687548010496) that it's not obvious how constant evaluation in Rust and C++ is similar or different. It took around ${1\over7}th$ of a second of thought until I had to strongly agree, because I have no clue what kind of tricks `constexpr` has up its sleeve. Now you may be wondering, why you'd read a comparison by someone who only knows one side of the coin. Behold, [the power of the internet](https://twitter.com/yaahc_/status/1206724961043222528): ![I don't know who the c++ constexpr expert is but whoever they are they should totally become friends with @oli_obk and collaborate to write an awesome blog post comparing the state of the art in const fn and constexpr](https://i.imgur.com/LmskO5L.png) I go to sleep before that tweet, and in the morning wake up to a list of experts that made this post possible. ## Usage This Post will have examples, and all of them will be executable. For this we'll be using the godbold compiler explorer. If there's implementation defined behaviour the C++ experiments may show both a gcc and a clang link. | Rust | C++ | | -------- | -------- | | https://rust.godbolt.org/ | https://clang.godbolt.org/ | | | https://gcc.godbolt.org/ | Let's dive into the first thing. How do you trigger constant evaluation? Both Rust and C++ made this nice thing where you explicitly say "make this const", by using a keyword specifically for this task: | Rust | C++ | | -------- | -------- | | `const` | `constexpr` | Although the keywords used may be confusing, because `C++` also has a `const` keyword, but it has a different meaning (mostly, sometimes it also has the same meaning, but for this post we can ignore that). ## First steps So, let's create our first C++ `constexpr`: <iframe width="100%" height="25px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:15,endLineNumber:1,positionColumn:15,positionLineNumber:1,selectionStartColumn:15,selectionStartLineNumber:1,startColumn:15,startLineNumber:1),source:'constexpr+int+two+%3D+1+%2B+1%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> This is fun, no code is generated, but we calculated the number `2` at compile time. Now the same thing in Rust: <iframe width="100%" height="25px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:24,endLineNumber:1,positionColumn:24,positionLineNumber:1,selectionStartColumn:24,selectionStartLineNumber:1,startColumn:24,startLineNumber:1),source:'const+TWO:+i32+%3D+1+%2B+1%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> So we can force things to happen at compile time, and the compiler does not write these things to disk. Of course if we wanted a variable with such a value, we could use the `two` (or `TWO` respectively) and then the value would in fact cause some machine code to be generated: <iframe width="100%" height="40px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:7,endLineNumber:2,positionColumn:7,positionLineNumber:2,selectionStartColumn:7,selectionStartLineNumber:2,startColumn:7,startLineNumber:2),source:'constexpr+int+two+%3D+1+%2B+1%3B%0Astatic+int+three+%3D+two+%2B+1%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> <iframe width="100%" height="40px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:29,endLineNumber:2,positionColumn:29,positionLineNumber:2,selectionStartColumn:29,selectionStartLineNumber:2,startColumn:29,startLineNumber:2),source:'const+TWO:+i32+%3D+1+%2B+1%3B%0Astatic+THREE:+i32+%3D+TWO+%2B+1%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> ## Function calls If you want to call functions from inside a `constexpr` or a `const`, you need to "take care" to only call functions that can actually be evaluated at compile-time. I put "take care" into quotes, because the compiler will actually tell you when you screw that up. This works by reusing both `constexpr` and `const` for function declarations: <iframe width="100%" height="40px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:32,endLineNumber:2,positionColumn:32,positionLineNumber:2,selectionStartColumn:32,selectionStartLineNumber:2,startColumn:32,startLineNumber:2),source:'constexpr+int+square(int+i)+%7B+return+i+*+i%3B+%7D%0Aconstexpr+int+four+%3D+square(2)%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> <iframe width="100%" height="40px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:11,endLineNumber:2,positionColumn:11,positionLineNumber:2,selectionStartColumn:11,selectionStartLineNumber:2,startColumn:11,startLineNumber:2),source:'const+fn+square(i:+i32)+-%3E+i32+%7B+i+*+i+%7D%0Aconst+FOUR:+i32+%3D+square(2)%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> This is where we get to the first difference between C++ and Rust const eval: > `constexpr` functions can call non-`constexpr` functions Before anyone starts getting excited about this difference, note that [this is also desired for Rust](https://github.com/rust-lang/const-eval/issues/7) out of performance reasons. Now that we got that out of the way, let's call a non-`constexpr` function from a `constexpr` function. We'll take the [well founded](https://www.xkcd.com/221/) scheme of returning the result of a fair dice roll in case `shim_rand` gets a `true` as the argument. ![](https://imgs.xkcd.com/comics/random_number.png ) In case a `false` is passed, we actually invoke `rand` which calls into the operating system and does all kinds of other non-`constexpr` shenanigans. <iframe width="100%" height="175px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:35,endLineNumber:11,positionColumn:35,positionLineNumber:11,selectionStartColumn:35,selectionStartLineNumber:11,startColumn:35,startLineNumber:11),source:'%23include+%3Crandom%3E%0A%0Aconstexpr+int+shim_rand(bool+shim_it)+%7B%0A++++if+(shim_it)+%7B%0A++++++++return+42%3B%0A++++%7D+else+%7B%0A++++++++return+rand()%3B%0A++++%7D%0A%7D%0A%0Aconstexpr+int+a+%3D+shim_rand(true)%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> And this works perfectly. We now have a `42` stored in `a` (`a` like `answer`). But of course you're all not here for the obvious parts. You wanna know what happens when we poke at `rand()`. Well, compiler errors happen. ## Calling non-const(expr) functions at compile-time First we get told where the evaluation of the constant started. This is basically like a backtrace from gdb, but at compile-time, and directly emitted by your compiler. If there were more stack frames, they'd all be listed here. ``` <source>:11:28: in 'constexpr' expansion of 'shim_rand(0)' ``` Then we get to the actual error. This is pretty much what we expected. We called a non-`constexpr` function from within a `constexpr` function. Just like a class function with a `const` modifier can't call a class function without a `const` modifier, this is forbidden. ``` <source>:7:20: error: call to non-'constexpr' function 'int rand()' 7 | return rand(); | ~~~~^~ ``` If you'd look at the definition of `rand` you'd not see a `constexpr` modifier there, so it's illegal for evaluation to actually reach this function call at compile time. Now you may wonder, why were you even allowed to write the call to `rand()` and only get an error if the call is evaluated. This is because a `constexpr` function is *not necessarily* called at compile-time. ![](https://i.imgur.com/WLZ2z3x.jpg) The `constexpr` modifier only makes sure that you *can* call the function at compile time. It doesn't stop you from now also calling it at runtime. Just because a function is declared as `constexpr` doesn't mean any call to it will be performed at compile time. As an example, let's go back to our `shim_rand` function and call it from some runtime code: <iframe width="100%" height="65px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:14,positionColumn:2,positionLineNumber:14,selectionStartColumn:2,selectionStartLineNumber:14,startColumn:2,startLineNumber:14),source:'%23include+%3Crandom%3E%0A%23include+%3Ciostream%3E%0A%0Aconstexpr+int+shim_rand(bool+shim_it)+%7B%0A++++if+(shim_it)+%7B%0A++++++++return+42%3B%0A++++%7D+else+%7B%0A++++++++return+rand()%3B%0A++++%7D%0A%7D%0A%0Aint+main(int+argc,+const+char**+argv)+%7B%0A++++std::cout+%3C%3C+shim_rand(argc+%3D%3D+1)+%3C%3C+std::endl%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> As you can see here, we used a runtime argument (`argc == 1`) which is a value we can't possibly know at compile time. Rust takes a stronger stance here and says you can't call non-const functions at all from const functions by directly erroring on the definition. ## Control flow Control flow means either branching or looping, so in C++ any of the following keywords: * `if` * `switch` * `while` * `do` * `for` and in Rust * `if` (and `if let`) * `match` * `while` (and `while let`) * `loop` * `for` but there's a significant difference between Rust's `for` and C++'s `for`: The Rust version uses static dispatch via a `trait` (in C++ that would be a template with concepts restricting the template parameters to subclasses of a specific class). This difference is significant, because in Rust it is not possible ([yet](https://github.com/rust-lang/rfcs/pull/2632)) to use `trait` bounds on generic code. This is under active development, so it's likely you'll see this feature on the nightly compiler within a few months. ### `if` and `switch`/`match` You've already seen `if` in the earlier `rand` example. So you already know the first difference between a C++ `constexpr` using `if` and a Rust `const` using `if`: The Rust version must be const evaluable no matter which branch is taken, the C++ version may error in one branch because it's not const evaluable. So what does "const evaluable" actually mean? We know from the previous example that `rand()` is not const evaluable, but `return 42;` is. Interestingly enough, in Rust, panicking (either explicitly via `panic!()` or implicitly by doing an out of bounds index operation), is const evaluable, but will result in an error. This is because no value for the constant could be computed, even though the constant's body was const evaluable. So "const evaluable" means to decide whether a constant can be evaluated without actually running constant evaluation. Actually running constant evaluation may fail even if the constant is const evaluable. You already know such a scheme from C++, and it's called duck-typing. A template declaration by itself will not error in C++ (barring syntax errors). In Rust, just like its generics forbid you from doing `+` on a generic value without an `Add` trait bound, you are forbidden from doing certain things in `const`s at the declaration. In C++ a `constexpr` is evaluated without having a first pass that decides whether to do this at all. See the [Compile Time Undefined Behavior](https://hackmd.io/k4RzURtCTXqLdbQO3aKrhQ?both#Compile-Time-Undefined-Behaviour) section for an explanation of why Rust can't just give you the same convenience as C++ (TLDR: it's UB in Rust). `switch` and `match` are essentially more powerful variants of `if` (Rust actually converts `if` to `match` inside the compiler). Thus, we apply the same reasoning we apply to the two branches of an `if`, to all branches of a `switch`/`match`. In Rust, all branches must be const evaluable. ### Loops Rust has `while (true)` built into the language. The `loop` keyword declares an infinite loop, and you manually need to use `break` inside to terminate the loop. <iframe width="100%" height="200px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:38,endLineNumber:3,positionColumn:38,positionLineNumber:3,selectionStartColumn:38,selectionStartLineNumber:3,startColumn:38,startLineNumber:3),source:'%23!!%5Bfeature(const_loop,+const_if_match)%5D%0A%0Aconst+FOUR:+i32+%3D+%7B%0A++++let+mut+i+%3D+42%3B%0A++++loop+%7B%0A++++++++if+i+%3D%3D+100+%7B%0A++++++++++++break%3B%0A++++++++%7D%0A++++++++i+%2B%3D+1%3B%0A++++%7D%0A++++0%0A%7D%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0'),(h:compiler,i:(compiler:nightly,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:rust,libs:!(),options:'',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'rustc+nightly+(Editor+%231,+Compiler+%231)+Rust',t:'0'),(h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+rustc+nightly',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> As previously mentioned, we can't use `for` in Rust yet, otherwise this would just be `for i in 42..=100 {}`. In C++ though, we can do just that: <iframe width="100%" height="100px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:4,positionColumn:2,positionLineNumber:4,selectionStartColumn:2,selectionStartLineNumber:4,startColumn:2,startLineNumber:4),source:'constexpr+int+bar()+%7B%0A++++for+(int+i+%3D+42%3B+i+%3C+100%3B+i%2B%2B)+%7B%7D%0A++++return+0%3B%0A%7D%0Aconstexpr+int+foo+%3D+bar()%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0'),(h:compiler,i:(compiler:g92,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.2+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0'),(h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+9.2',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> ### `return`, `throw` and `panic` The final form of control flow is an early return either via the regular `return` path or via exception throwing or `panic` respectively. I am mentioning all of these in a mangled manner, because in Rust there are no exceptions, instead you return an `enum` (tagged union in C++ terms) with an `Err` variant and an `Ok` variant holding either the error information or the successfully computed value. C++'s `throw`, similar to `rand()` calls, is not allowed to actually end up being evaluated at compile-time. Since Rust's "exceptions" (enum return types) are just regular values, Rust can use its idiomatic error reporting scheme, even in constants. "What about `panic`?" you may ask. Good question. Rust's `panic` is different from `throw`, because it should never be caught. It will cause unwinding to happen and destructors to be called, but there's no reason to catch panics outside of FFI and some other rare safety related use cases. This allow Rust to employ a neat trick: a `panic` doesn't have to actually do the unwinding and destructor invocation, since by definition destructors in const eval cannot have side effects. So if you call `panic!` in a constant in Rust, you get a compile-time error and that's it. ## Compile Time Undefined Behaviour Naively all of these restrictions sound like "Rust forbids me from doing nice things". This is actually how I got into contributing to the Rust compiler. I wondered why we can't have cool features, started adding them without thought and suddenly you could do UB in safe Rust. So these checks are actually there to prevent you from doing Undefined Behaviour. This doesn't mean you can't have those features in Rust, it just means they need a bit more work than just allowing them to compile successfully for the correct cases. We also need to make them not compile successfully for incorrect cases. In C++ you get all the nice features immediately, but you need to prove that you are using them correctly. Since C++ compile-time UB is already explained by [Shafik](https://shafik.github.io/c++/undefined%20behavior/2019/05/11/explporing_undefined_behavior_using_constexpr.html) much better than I ever could explain it, I'm not going to go into this into more detail here. But I am going to touch on the "Guaranteed Copy Elision" example from Shafik's post. The TLDR is that you can have type system UB by making const eval affect types used in the very same const eval. So you get a situation where a constant's value is `true` only if it is `false`. Rust does not have this as it errors on any kind of cyclic dependency in the type system. This may mean, that in some situations constexpr is and will always be more powerful. But since Rust's type system is turing complete, I'm guessing that you could still get the non-UB cases to work with a bit of type system magics. ## Types of constants I talked a bunch about how Rust isn't permitting us to do a few things because UB (... handwaving intensifies). To be able to explain these situations, we'll need to have a look at what kind of types Rust and C++ permit as `constexpr`/`const` variables and function return types. `constexpr` requires all such types to be [LiteralType](https://en.cppreference.com/w/cpp/named_req/LiteralType). This means that e.g. the destructor of the type must be `constexpr` and there must be at least one non-copy/move `constexpr` constructor. In Rust all types are legal for return types (if they are legal as return types of normal functions). It may just be that there's no way to construct a value of that type at compile-time. For `const` items there is one major restriction: the *value* may not contain references to types with interior mutability (e.g. `Cell` and `RefCell`). <iframe width="100%" height="45px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:21,endLineNumber:1,positionColumn:21,positionLineNumber:2,selectionStartColumn:21,selectionStartLineNumber:2,startColumn:21,startLineNumber:2),source:'use+std::cell::Cell%3B%0Aconst+BAR:+Cell%3Ci32%3E+%3D+Cell::new(42)%3B%0Aconst+FOO:+%26Cell%3Ci32%3E+%3D+%26BAR%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0'),(h:compiler,i:(compiler:nightly,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:rust,libs:!(),options:'',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'rustc+nightly+(Editor+%231,+Compiler+%231)+Rust',t:'0'),(h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+rustc+nightly',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> is not legal, because `FOO` contains a reference to something with interior mutability. On the other hand <iframe width="100%" height="80px" src="https://rust.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:38,endLineNumber:5,positionColumn:38,positionLineNumber:5,selectionStartColumn:38,selectionStartLineNumber:5,startColumn:38,startLineNumber:5),source:'use+std::cell::Cell%3B%0Aconst+BAR:+Cell%3Ci32%3E+%3D+Cell::new(42)%3B%0Aconst+BEP:+Option%3CCell%3Ci32%3E%3E+%3D+None%3B%0Aconst+FOO:+%26Option%3CCell%3Ci32%3E%3E+%3D+%26BEP%3B%0Aconst+FOP:+Option%3C%26Cell%3Ci32%3E%3E+%3D+None%3B'),l:'5',n:'0',o:'Rust+source+%231',t:'0'),(h:compiler,i:(compiler:nightly,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:rust,libs:!(),options:'',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'rustc+nightly+(Editor+%231,+Compiler+%231)+Rust',t:'0'),(h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+rustc+nightly',t:'0')),k:44.55263900649168,l:'4',m:100,n:'0',o:'',s:0,t:'0')),version:4"></iframe> is perfectly legal because you don't actually have a `Cell` value behind a reference. The reason you can't have mutation behind a reference is that `const` items are essentially bit copied to all their use sites (but it's not guaranteed that they are). So if you did `FOO.set(0)` in some code, and `FOO.set(9)` in some other code, it would depend on optimizations whether you'd be modifying the same object or a different one. ## Heap Amusingly, at the time of writing this post, the 4th result on google for "c++ heap allocation constexpr" is https://github.com/rust-lang/const-eval/issues/20 which I opened to discuss heap allocations in Rust. ## Pointers ## Function pointers <iframe width="100%" height="120px" src="https://clang.godbolt.org/e?readOnly=true&hideEditorToolbars=true#g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:27,endLineNumber:6,positionColumn:27,positionLineNumber:6,selectionStartColumn:27,selectionStartLineNumber:6,startColumn:27,startLineNumber:6),source:'constexpr+int+foo()+%7B+return+42%3B+%7D%0A%0Atypedef+int+(*fptr)()%3B%0A%0Aconstexpr+fptr+mep+%3D+%26foo%3B%0Aconstexpr+int+bar+%3D+mep()%3B'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0'),(h:compiler,i:(compiler:g92,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.2+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0'),(h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+9.2',t:'0')),k:100,l:'4',n:'0',o:'',s:0,t:'0')),version:4"></iframe> ## Thanks * [Jane](https://twitter.com/yaahc_) for exploding the visibility on this * [ubsan](https://twitter.com/ubsanitizer) * [Shafik](https://twitter.com/shafikyaghmour) for writing about `constexpr` and UB * [Sy](https://twitter.com/TartanLlama) * [Jason](https://twitter.com/lefticus)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully