9 ms·
Lvalues, rvalues, glvalues, prvalues, xvalues, help (2018)
- somedudeatwork 8y agolvalues are locatable, they represent an object that occupies some identifiable location in memory (has address). rvalues do not and therefore cannot be addressed (with & or *) I think of lvalues as things on the stack and rvalues as things stored in registers https://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c/ https://eli.thegreenplace.net/2011/12/15/understanding-lvalu...
- dbaupp 8y agoThe article starts by explaining lvalues and rvalues more precisely than that, and breaks them up into 3 additional value categories in modern C++ (the ones in the title). (Also, lvalues aren't tied to the stack: they can be anywhere in memory, like heap or static.)
- leetcrew 8y agohow can you have an lvalue stored in the heap? isn't the lvalue itself a pointer in the stack? obviously I see how it can have static storage.
- dbaupp 8y agoIf foo is an lvalue, then I believe (for example) *(foo[0].bar->baz) is also an lvalue, and those pointer dereferences can go anywhere. Those values occupy a location in memory, as you said, even if it isn't on the stack.
- leetcrew 8y agooh okay, understood. frankly I don't have an airtight understanding of the c++ standards and I would have considered your expression to be a dereference operation on an lvalue, but not an lvalue itself. ty for the explanation!
- simiones 8y agoI'm sure there are some complex exceptions, but as a starter, you can think of lvalues as "anything you can assign to" (the l basically stands for left, as in, "can appear on the left of an assignment"). So, if you have something like `foo(val) = 10`, then `foo(val)` is an lvalue.
- mannykannot 8y agoOne of the complications is that if you take an l-value and const-qualify it, it is still an l-value (but not a modifiable l-value.) https://www.geeksforgeeks.org/lvalue-and-rvalue-in-c-language/ https://www.geeksforgeeks.org/lvalue-and-rvalue-in-c-languag...
- mannykannot 8y agoThey are not mutually exclusive. When a pointer has been set to point to an lvalue, dereferencing it yields that lvalue.
- gumby 8y agoglobal variables are lvalues, for instance.
- jstimpfle 8y agoC99 actually lets you make "pointer literals" (dont know the proper name) by putting an addressof operator in front of rvalue expressions. I cant offer a better explanation than the one you gave, though.
- quietbritishjim 8y ago> rvalues do not and therefore cannot be addressed (with & or *) Correction: prvalues cannot be addressed. There are also xvalues, which are both rvalues and lvalues i.e. they can be addressed but can also be moved from. In practice I think these are always lvalues that have been cast to an rvalue reference, usually using std::move().
- mannykannot 8y agoThis thread is recapitulating the article.
- twic 8y agoI used to think that. It's simple, right? Then i said so on the C++ Slack and got the hell beaten out of me. In modern C++, lvalue and rvalue simply don't mean what they do in other languages. Wild but true.
- ncmncm 8y agoLvalue and rvalue are inventions that serve a particular purpose in Algol-family languages. They are not physics. These other value categories are further inventions for additional purposes. The only unfortunate bit is the insistence on one-letter abbreviations when discussing them.
- notacoward 8y agoExcellent explanation. Too bad it's necessary. && and std::move are the biggest warts in C++ (that's saying a lot), representing the need for programmers to be constantly aware of the less-than-obvious ways that a compiler might put an expression in one category or another. It's the programmer helping the compiler, instead of the other way around as it should be. In general, if I need an rvalue and it's legal to convert the lvalue I have into an rvalue, the compiler should do it automatically. Having to make it explicit should be the exception, not the rule. The compiler does many other kinds of inference and automatic promotion/conversion, some of them far more difficult (and dangerous). Why not this one? I suspect the reason has less to do with the actual ergonomics of producing correct programs than with the the interests and self-image of those creating the standards.
- xhgdvjky 8y agosuppose you have a shared ptr and you pass it to a function with overloads for move and value. what should the compiler deduce? it can't tell if it's legal. it can't tell if it's illegal I agree this is a nasty thing to rely on, but id rather be verbose and know what's happening than have more deduction guides/similar
- notacoward 8y agoIf the compiler can't deduce what to do or whether it would be safe then sure, it should require the programmer to disambiguate. The keywords and underlying mechanisms should exist, just as with type casts and such. However, I see a lot of cases where what the intent is obvious and the result obviously safe. Often the compiler even manages to identify the one reasonable answer, but instead of applying it or at least presenting it to the user in readily applicable form it throws an error with the answer converted into standards-ese and surrounded with a dozen lines of irrelevant context. That's not helpful. I've worked on a lot of large old C codebases, mostly kernels and filesystems. Every one has developed its own way to handle issues of object lifetime, ownership, etc. I've seen dozens of implementations of automatic reference counting, borrowing, weak references, and so on. Some of them have been widely and rightly regarded as awful and a pain to use, but none of them were as bad as the mess that C++ imposes on a much larger audience. I see a lot of my colleagues submit to Stockholm Syndrome and accept it as the proper way of the world, but I'm not inclined to follow their lead without registering my objections first.
- rocqua 8y agoIs it totally exactly true that a `glvalue` is either an `xvalue` or a `lvalue` and nothing else? Similarly, is a `rvalue` either a `xvalue` or a `prvalue`?
- dbaupp 8y agoYes, section 8.2.1 "Value Category" (page 80) of the C++17 standard[0] defines the terms as: (1.1) - A glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function. (1.2) - A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears. (1.3) - An xvalue is a glvalue that denotes an object or bit-field whose resources can be reused (usually because it is near the end of its lifetime). (1.4) - An lvalue is a glvalue that is not an xvalue. (1.5) - An rvalue is a prvalue or an xvalue. It also has a diagram summarising it (equivalent to the one in the article, but the article's is clearer IMO): expression / \ glvalue rvalue / \ / \ lvalue xvalue prvalue Where every expression is in one of the three value categories in the bottom row. [0]: available free as a late draft: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n471...
- rocqua 8y agoThanks, I actually recall seeing that diagram. I agree that the article is clearer. Because I didn't get it when I saw that diagram, but I do get it after reading the article.
- meuk 8y agoArticles like this make me feel very smug about my decision never to go down the rabbithole of learning C++. I feel perfectly comfortable with using pointers (and my intuition about them) in C.
- chubot 8y agoFWIW I mostly use “out params” as in C because I think moves incur a lot of complexity, as well explained in this article. It’s also more lines of code to write. Some people may quibble with it but I think it’s still a fine style of writing C++, and in fact most C++ you’ll see is written like that, since this is a new-ish feature.
- strictfp 8y agoAgreed. RVO is not guaranteed, and move is complex. Smart pointers have overhead. Out params are for the most part a sensible choice in C++. Sadly. I'm honestly shocked that this problem hasn't been addressed in a better way.
- RcouF1uZ4gsC 8y agoRVO is guaranteed in C++17
- ncmncm 8y agoOut-parameters are a terrible choice in C++. If it matters whether RVO is guaranteed, you are probably making something more complicated than it needs to be. Value semantics give you sensible behavior. Smart pointers should not appear in user-visible interfaces. It is easy to tie yourself in knots by doing the complicated thing. The solution is to do the simple thing.
- notacoward 8y ago> It is easy to tie yourself in knots by doing the complicated thing. The solution is to do the simple thing. Good advice. Corollary: don't use tools that make it hard to do simple things, or force you to live with the not-simple things others have done.
- bagol 8y agoIs this concept of lvalues, rvalues, glvalues, prvalues and xvalues only exists in C++?
- Sharlin 8y agoFew other languages have move semantics. Rust does, but has a quite different value model overall.
- cesarb 8y agoAlso, Rust does not have copy or move constructors/operators; every copy or move is a pure memcpy() (there's Clone for when you need it, but clone is always an explicit call). This simplifies the model a lot.
- htfy96 8y agoC++'s move constructor can throw exceptions. An example would be moving a linked list, and the allocation of dummy tail node can fail. In my opinion, the design choice to support recoverable allocation failure in C++ reasons for most other designs.
- steveklabnik 8y agoYou can make allocation failure recoverable in different ways. For example, Rust’s (yet to be stabilized) allocator API returns a Result: https://doc.rust-lang.org/stable/std/alloc/trait.Alloc.html#tymethod.alloc https://doc.rust-lang.org/stable/std/alloc/trait.Alloc.html#... It is true that choosing to make this recoverable is a big part of it; in Rust we decided to make standard library data structures treat allocation as unrecoverable, and this does simplify the API of using them significantly. However, I would argue that the complexity in C++ comes more from using exceptions for this purpose than from that choice. Rust’s panics being used for unrecoverable errors only helps simplify the overall model. In other words, the ease of use goes unrecoverable > recoverable through result > recoverable through exceptions, and the model complexity comes from the choice of using exceptions over return values. We do have a plan for introducing a way to make the data structures recoverable, but it’s waiting on several things. This is, of course, only my opinion.
- Jeaye 8y agoSimilarly, the value category cheatsheet: https://github.com/jeaye/value-category-cheatsheet/blob/master/value-category-cheatsheet.pdf https://github.com/jeaye/value-category-cheatsheet/blob/mast... and more info on xvalues: https://blog.jeaye.com/2017/03/19/xvalues/ https://blog.jeaye.com/2017/03/19/xvalues/
- agallego 8y agogreat post!
- contravariant 8y agoMaybe this is just naive / wishful thinking, but wouldn't it have made way more sense to go with either: glvalues, lvalues, grvalues, rvalues, xvalues or lvalues, plvalues, rvalues, prvalues, xvalues ?