News for hackers. Stuff that matters.
Re:Add a const here, delete a const there by chamakits on Monday January 09, 2017 @08:13AM (#13356074)
WARNING:

I believe the site has some malware injected in it. At least the mobile version of it. After a few second it redirected me to some site with a fake Facebook skin.

Re:Add a const here, delete a const there by lorenzhs on Monday January 09, 2017 @08:58AM (#13356299)
Once again, this demonstrates that blocking advertisements is a really good idea from a security perspective. It doesn't just reduce clutter and speed up page loading times, but also prevents loads of malware issues. See also https://twitter.com/swiftonsecurity/status/62840155490772582...
Re:Add a const here, delete a const there by iokanuon on Monday January 09, 2017 @03:16PM (#13359431)
AdAway's Android host file seems to block it just fine, you don't even need a fancy adblock plugin.
Re:Add a const here, delete a const there by dzdt on Monday January 09, 2017 @08:36AM (#13356187)
I confirm this mal-redirect on mobile.
Re:Add a const here, delete a const there by josteink on Monday January 09, 2017 @11:04AM (#13357285)
Firefox mobile unaffected.
Re:Add a const here, delete a const there by dzdt on Monday January 09, 2017 @08:49AM (#13356259)
This is begging for a C++ FQA style hate blog post. Paging Yossi Kreinin? Seriously, "Delete const three times to move 53,064 bytes to read-only data segment and save 729,168 bytes of code." WTF?

[1] http://yosefk.com/c++fqa/index.html

[2] http://yosefk.com/blog/

Re:Add a const here, delete a const there by lmm on Monday January 09, 2017 @09:46AM (#13356635)
It's MSVC only. They're going to fix it. And it doesn't affect the semantics, only performance. I mean sure, it's a bug, but it's not FQA territory.
Re:Add a const here, delete a const there by digler999 on Monday January 09, 2017 @12:56PM (#13358186)
as others pointed out, its the compiler. but maybe this requires a Microsoft FQA. Maybe these compiler "bugs" are really more microsoft "anti-features" designed to slowly erode people's faith in C++ on MS platforms and nudging them toward C# or other .NET "solutions" ?

I just can't believe that one of the biggest monolithic organizations with unlimited budgets and decades of experience developing tools for their own platform(!!) would make such careless mistakes or miss out on rather obvious optimizations. And it also sickens me that random devs out there are wasting hours of their lives doing completely unpaid MS product QA work. At least when jobs are outsourced to the third-world, the laborers are paid something.

Re:Add a const here, delete a const there by goalieca on Monday January 09, 2017 @04:05PM (#13359781)
Microsoft compilers are dramatically improved since the VS 6.0 days. The days before C# and vista. The days before herb sutter came in to save us.
Re:Add a const here, delete a const there by masklinn on Monday January 09, 2017 @12:08PM (#13357815)
It's a compiler issue, nothing to do with C++ so wouldn't be an FQA entry.
Re:Add a const here, delete a const there by CalChris on Monday January 09, 2017 @12:21PM (#13357906)
I can see that the removing const case is a compiler issue. How is the adding const case a compiler issue? Shouldn't the result be the same on Clang and GCC?
Re:Add a const here, delete a const there by sqeaky on Monday January 09, 2017 @12:28PM (#13357958)
That adding const open optimization opportunities for the compiler is not surprising to anyone who knows what const is for. Removing const to cause optimization is a big wtf and that is why it is worth debating.
Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @08:59PM (#13361897)
Actually, with the exception of the modest benefits from moving globals to the read-only data segment it is rare to get optimization benefits from tagging something as const.

const is for enforcing correctness by the compiler. It tells the compiler about intent, but it doesn't give the compiler any extra information that it can use for optimizing.

Example: If you mark a member function as const then the compiler knows that you can't modify member variables. However the compiler won't use that to optimize the function - what it will use is its own data flow analysis that independently shows that you aren't modifying any member variables.

The distinction becomes important if you call some non-member function whose definition is not visible. At that point the compiler has to assume that that function might modify the object, though a separate cached pointer. So, the fact that the member function is const becomes useless as soon as the the compiler can't analyze code flow anymore.

I believe.

Re:Add a const here, delete a const there by sqeaky on Tuesday January 10, 2017 @12:13PM (#13366535)
I think this way of looking at it old. Even if the const-ness is somehow subverted without generating an error then most compilers (or at least GCC and Clang) will presume the code is compliant and make optimizations following what the standard allows. This potentially results in undefined behavior when that pointer you mentioned is used to modified a thing that ought to be const.

Consider the amount of optimizations seen in the video from CppCon 2016: https://www.youtube.com/watch?v=zBkNBP00wJE

Jason Turner, the presenter, is writing code a few lines at a time and cross compiling for the Commodore 64. He shows his assembly at many steps of the way and shows how many functions are completely elided when const (and later constexpr) are used correctly.

There are a ton of other good talks from CppCon 2016 including one about const and what optimizations it makes possible and several about how compilers are more willing to "break" code that is non-compliant by making its behavior undefined. None of it really shocking or new, unless you have been writing to one compiler implementation instead of to the standard.

Re:Add a const here, delete a const there by brucedawson on Friday January 13, 2017 @08:56PM (#13396370)
> None of it really shocking or new, unless you have been > writing to one compiler implementation instead of to > the standard.

I think you should focus more on giving concrete examples instead of making snide comments.

And, I'm not going to watch an eighty minute video in order to find out what you are talking about. Specific examples would be appreciated.

I agree that tagging globals as const can help the optimizer. If that is what you were talking about then I have no disagreement. However I have seen many people who expect speed wins when they tag member functions as const, or local variables as const. In those cases it is rare for 'const' to improve code-gen.

Re:Add a const here, delete a const there by sqeaky on Tuesday January 17, 2017 @01:05PM (#13419650)
I was not attempting to be snide or rude. You are free to take the very concrete example I provided or not. You cannot say I didn't provide any.

The instant where the const keyword removes 95+% of the generated machine code is just after 28:00, but you should watch from at least a few minutes before that to establish context. That wasn't a global he put it on, but it wasn't a member variable either.

I recommend watching the whole talk, because the whole thing is pertinent to what optimizing can and cannot do. Because the speaker wants to get modern software onto an old machine he works around tight constraints while getting all of C++17. If you choose not to ignore something that you have expressed an interest in and is pertinent then you are doing something far worse than being rude and you are doing it to yourself.

Go benchmark you code, I have benchmarked mine. Putting const everywhere applicable helps even back in the pre-C++11 days. I state again not trusting and working with your optimizing compiler is simply an old an outmoded way of thinking.

Re:Add a const here, delete a const there by masklinn on Monday January 09, 2017 @04:31PM (#13359990)
Where data is put is a compiler decision, I don't believe the C/C++ specs even have concepts of data segments so they wouldn't specify where to store r versus rw versus rx data, let alone how the OS would handle their sharing.
Re:Add a const here, delete a const there by CalChris on Monday January 09, 2017 @07:04PM (#13361234)
Linker decision with compiler information.
Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @09:01PM (#13361905)
Adding const to globals is useful on most or all compilers. It deserves mention in C/C++ FAQs as a best practice. You can see this for yourself with simple test apps using gcc and clang.

The C++ standard doesn't mandate this, but good toolchains do put constant data in a separate read-only segment.

Re:Add a const here, delete a const there by tech2 on Monday January 09, 2017 @05:07AM (#13355261)
I'm interested in the possible security improvements in the change which didn't seem to be mentioned at all. Is all this data already in an NX area, or was it somehow already protected via some other means?
Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @12:20PM (#13357898)
None of the pointers were code pointers so there are probably no security improvements. It might protect Chrome from a few hard to diagnose crashes because now if a stray write hits those arrays it crashes instantly instead of misbehaving later.
Re:Add a const here, delete a const there by xyzzy123 on Monday January 09, 2017 @05:18AM (#13355295)
Already nx but rw -> r with some code (rx) removed also. Not really security improvements from a w^x perspective.
Re:Add a const here, delete a const there by revelation on Monday January 09, 2017 @06:19AM (#13355534)
For embedded systems that extra const can mean the difference between having that data in SRAM or Flash.
Re:Add a const here, delete a const there by cixin on Monday January 09, 2017 @05:02AM (#13355245)
Wow awesome! It's partly these little optimizations that keeps C/C++ going.

I've never considered that const might have a performance benefit (and mostly just use it as a compile time check). But will consider it in the future.

Would be interesting to see performance benchmarks for the changes made here, as well as applying const in general.

Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @08:51PM (#13361858)
Ignoring the VC++ compiler bug/quirk, the benefits for adding const tend to be small and hard to measure. How do you measure the possible reduction in private pages? How do you measure the productivity gains from slightly fewer corrupted globals.

Usually you don't. You just tag your const globals as such and then get on with your day. Once you develop the habit the cost is zero so measuring the benefits isn't necessary.

Re:Add a const here, delete a const there by adrianN on Monday January 09, 2017 @05:10AM (#13355271)
So will they put the consts back after the VS bug is fixed?
Re:Add a const here, delete a const there by rkangel on Monday January 09, 2017 @06:41AM (#13355619)
If all the of the things which have had 'const' removed are members of structs that are themselves 'const', then there is no need to re-add them.
Re:Add a const here, delete a const there by bla2 on Monday January 09, 2017 @09:48AM (#13356649)
MSVC is such a bad compiler. Yes, they are working on it, it's getting better, but this is apparently a fairly new regression.
Re:Add a const here, delete a const there by gcp on Monday January 09, 2017 @11:29AM (#13357516)
Working around the following bug caused Firefox's size to drop by over 200k. We should try fiddling with const, too :-)

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78323

Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @12:28PM (#13357956)
Chrome continues to use MSVC on Windows because it generates better code than clang. So, MSVC is the worst compiler, except for the alternatives?
Re:Add a const here, delete a const there by Joky on Monday January 09, 2017 @06:41PM (#13361048)
I believe I read that it is rather that clang is (was?) not feature complete (until recently at least) for debugging in MSVC. Support for PDB/Codeview is very recent in clang, and I'm not sure it is complete yet.
Re:Add a const here, delete a const there by obl on Monday January 09, 2017 @01:00PM (#13358229)
Would appreciate a reference on that if you have it handy.

Is this more of a whole program measured X% regression on some perf benchs, or specific target cases where the codegen is notably worse ?

Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @08:49PM (#13361844)
I should probably take back my claim because I can't find the evidence to back it up and I might actually be wrong. I thought I remembered that there were some important cases where VC++ generated better code for Chrome, and some binary size advantages, but I can't find my references.
Re:Add a const here, delete a const there by brucedawson on Friday January 13, 2017 @08:59PM (#13396380)
crbug.com/457078 talks about binary size in clang-cl versus VC++. On x86 builds clang-cl produces ~14% larger binaries. On x64 builds it produces ~3.5% smaller binaries.

My recent changes have made the comparison tougher for clang-cl by making the VC++ binaries smaller :-)

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @06:22AM (#13355542)
In my experience you should NEVER have const instance fields. Ever. If you want a const reference, just make a pointer to const. If you need a const value, just leave it mutable and access it through a const getter or work around it some other way. The language just doesn't seem to have been designed to make this particular feature actually worthwhile.
Re:Add a const here, delete a const there by wyldfire on Monday January 09, 2017 @09:26AM (#13356472)
What's the drawback for a const member?

IMO `const` should be used liberally: members, locals and other declarations.

When you're on a team and you have a data structure that has const members, it should give that newer/unfamiliar team member pause when they get the compilation error because they added a method that modifies the `const` member. Now they have an opportunity to take a step back and ask "Oh, why was it designed this way? What other assumptions in the code are invalidated if I need to remove the `const`?"

`const` for locals is good for those notorious ten-line functions that over time multiply into a 150-line function. Yes, we should refactor that mega function into something easier to digest. But right now I am trying to figure out this bug: I can see that ^^ up there 'foo' was initialized as a particular value, and down here it looks like it must have changed. Instead of looking through all of the hundred lines of code to see who might've updated 'foo', I know right away that a likely explanation is stack corruption.

This is BTW why I love that rust has opt-in mutability. It feels almost a little silly sprinking `const` thither and yon when it's only a few select places that it's actually un-needed.

Re:Add a const here, delete a const there by brucedawson on Monday January 09, 2017 @12:26PM (#13357946)
Author here. I'm a big believer in adding const everywhere - local variables, globals, member functions, etc.

Marking globals as const can move them to the read-only segment which has some modest performance improvements, but in most other cases const doesn't affect code-gen at all. Using const prevents programmers from doing certain things, and the compiler enforces that. That suggests that the compiler already knows whether or not programmers are doing those things - it doesn't need a 'const' hint to tell it. And in those cases where it can't tell, the 'const' hint is usually not sufficient for it to depend on.

In short, with the exception of moving globals to the read-only segment I am not aware of any performance improvements from using const.

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @03:31PM (#13359514)
> What's the drawback for a const member?

Check out this subthread: https://news.ycombinator.com/item?id=13356101

Re:Add a const here, delete a const there by keldaris on Monday January 09, 2017 @07:32AM (#13355851)
It's very worthwhile for performance, and somewhat helps limit basic programmer errors. I can't imagine a single reason to tell people not to use const instance fields. On the other hand, telling people not to treat const as an absolute guarantee is obviously good advice and what you said about const& and getters is spot on.
Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @07:42AM (#13355909)
You're gonna need a citation (preferably, an example) for the performance claim.

As for this comment of yours:

> I can't imagine a single reason to tell people not to use const instance fields.

That's weird, did you not read the blog post? It literally gave you a reason not to, you don't need to imagine anything. If you don't think it's a compelling reason then that's another story, but it's a valid reason.

Re:Add a const here, delete a const there by keldaris on Monday January 09, 2017 @07:59AM (#13356010)
It's impossible to provide general benchmarks, since the impact will be completely case specific. However, the reason I didn't provide a citation is because the OP already gives an example - blink::serializedCharacterData gets moved over the read-only data segment if you add const, with obvious consequences for, say, thread-local accesses in tight loops. In my own code, I've seen adding a const modifier result in 20-60% perf improvement in fairly extreme cases. In other cases (probably most cases), it won't change much.

More importantly, I've never seen an example where adding const would ever decrease CPU performance by any amount at all (other than compiler bugs, which can ruin any language feature). Accordingly, my personal recommendation is that everything that can be const should be. It's an easy thing to do that may help and definitely won't hurt.

> That's weird, did you not read the blog post? It literally gave you a reason not to, you don't need to imagine anything. If you don't think it's a compelling reason then that's another story, but it's a valid reason.

That's an outright compiler bug, not a general language reason. Obviously, it's a valid caveat if you're using that specific compiler and care about that edge case, but it's hardly a general argument.

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @08:17AM (#13356101)
> However, the reason I didn't provide a citation is because the OP already gives an example - blink::serializedCharacterData gets moved over the read-only data segment if you add const, with obvious consequences for, say, thread-local accesses in tight loops.

Uh, that wasn't an instance field, was it? https://codereview.chromium.org/2608823002/diff/20001/third_...

> That's an outright compiler bug, not a general language reason.

It's not a bug, just a missed performance optimization. The code behaves correctly.

And I was merely responding to your comment, "I can't imagine a single reason to tell people not to use const instance fields."

The underlying language reason I have for it is not something you may agree with, but it's that it Seems Wrong (TM) to me for the fields of a class to dictate how the class's instances can be constructed or assigned to. Again, I don't claim I can convince you here. It just seems like poor design to me, and it's given me trouble so many times without once actually providing me a benefit. So it's a reason. YMMV.

Re:Add a const here, delete a const there by keldaris on Monday January 09, 2017 @08:45AM (#13356239)
> Uh, that wasn't an instance field, was it? https://codereview.chromium.org/2608823002/diff/20001/third_....

Fair point, I was indeed being insufficiently precise. That code is a typical example of how const helps performance, concrete performance gains from applying const to instance fields in particular are much rarer in practice.

> It's not a bug, just a missed performance optimization. The code behaves correctly.

I think the MSVC devs classify it as a codegen bug since the cause is a logic error in the optimizer. The code does behave correctly, but it's reasonable to expect that optimization to happen, and it does in GCC / clang. My point here is simply that in this case MSVC is the outlier, therefore the example does not constitute a general argument against using const in this context.

> The underlying language reason I have for it is not something you may agree with, but it's that it Seems Wrong (TM) to me for the fields of a class to dictate how the class's instances can be constructed or assigned to.

I happen to have the opposite preference, namely that if you have constant data in a struct, it makes sense to say so at the declaration site for clarity. Regardless, it's a perfectly reasonable stylistic preference. I only argued against it because the phrase "NEVER have const instance fields. Ever." seems much too strong for what's ultimately a subjective choice. In doing so, however, I may have erred in the opposite direction and made overly strong statements myself. Mea culpa.

> It just seems like poor design to me, and it's given me trouble so many times without once actually providing me a benefit. So it's a reason. YMMV.

It's definitely a valid personal preference. When you say using const has given you trouble many times, do you have any particularly poignant example in mind?

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @03:30PM (#13359511)
> Fair point, I was indeed being insufficiently precise. That code is a typical example of how const helps performance

OK, well, I was merely saying you need a citation for the situation we were discussing. I still stand by it.

> I think the MSVC devs classify it as a codegen bug since the cause is a logic error in the optimizer.

I'm gonna pull your own type of argument here, which is that they only consider it a bug because they have their own stricter guidelines for what they expect, not because it's actually a general language implementation bug. Definitely not something I'd call an "outright compiler bug" when the code is behaving sanely.

> When you say using const has given you trouble many times, do you have any particularly poignant example in mind?

I don't have a particularly poignant one at the top of my head right now, but I can give you a hypothetical one to illustrate the idea. Look at std::binary_negate (for our purposes assume the functor is required to be const-callable). People put const on the instance field of that sort of thing because, well, everything that can be const should be const dammit! Except now it gives you hell trying to assign to the object. That's the issue.

Re:Add a const here, delete a const there by Arnt on Monday January 09, 2017 @08:11AM (#13356067)
You can overload on const in C++, so int a(foo b) and int a(const foo b) can coexist. We used this in Qt 2.0, there were a few cases where we could get significantly more oomph if we knew the argument was const.

Ff a function takes a struct (or class) as argument can calls otherfunction(foo.bar), then the constness of foo's bar field matters. The same might apply to fields of this.

Re:Add a const here, delete a const there by pontobart on Monday January 09, 2017 @04:58PM (#13360212)
You cannot overload on the const. If you try to define both int a(int b) and int a(const int b) the compiler will complain about a redefinition.

You can declare the function using int a(int b) in the header and then define it via int a(const int b).

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @08:19AM (#13356107)
Nobody said it doesn't "matter" whether you put const. I was saying it's not worthwhile.
Re:Add a const here, delete a const there by phaedrus on Monday January 09, 2017 @02:57PM (#13359284)
I think you're getting downvoted because you asserted advice as an absolute and gave no explanation why/when it applies. I happen to agree with you empirically, but I would phrase it thus: const member variables can be problematic in C++ because it disables some of the compiler-generated functions such as memberwise assignment. It violates the law of least astonishment because it seems natural to use const for the members of a small "value type" (e.g. Point, Complex, etc.) and it seems natural to store such objects in std container (e.g. std::vector), but adding the "const" on the member fields makes the object incompatible with the std containers.
Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @03:32PM (#13359529)
Yeah, you're saying more or less what I was thinking here. https://news.ycombinator.com/item?id=13356101 Indeed I should've written it in the original comment.
Re:Add a const here, delete a const there by revelation on Monday January 09, 2017 @07:38AM (#13355889)
I'm also with the VC team here, a const but not static instance field? Their stance seems correct that that should be initialized - in a constructor.
Re:Add a const here, delete a const there by brucedawson on Tuesday January 10, 2017 @01:28AM (#13363096)
VC++ 2010 used to think that too and would generate warning C4610 for const non-static members. However that warning was wrong, and was changed to not fire in that case. See this link:

https://connect.microsoft.com/VisualStudio/feedback/details/...

Re:Add a const here, delete a const there by wfunction on Monday January 09, 2017 @07:46AM (#13355927)
Not sure why you replied to my comment (seems like an unrelated comment?), but anyway, this should work too; you shouldn't need a constructor:

  struct { const int x; } y = { 1 };
Re:Add a const here, delete a const there by voltagex_ on Monday January 09, 2017 @05:27PM (#13360411)
Offtopic sidenote: I wish more open source projects had instructions as good as https://www.chromium.org/developers/how-tos/debugging-on-win...