C++: Why Use const?

Started by
32 comments, last by snk_kid 19 years, 5 months ago
Quote:Original post by Roboguy
Also it takes up less memory.


Are you joking?
Advertisement
I'd just like to point out that while const IS meant for humans, it can actually help the compiler optimize as well. It shouldn't work that way, but there was code posted here on gamedev that showed (via the assembly ouput) that const made VS.Net 2003 optimize better.

It was for the vector class with members x,y,z,w that could also be accessed as [0] to [3]. The array used for [0] to [3] was only optimized away when it was made const, so without the const the compiler was leaving out a pretty big optimization (presumably because of aliasing issues).
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Quote:Original post by DudeMiester
Ok I have this weird issue. Basically what I have is this:

const T func1(){    T Result;    return Result;}const T func2(){    return T();}


Now I would figure both functions would be identical, but upon testing it turns out that func2 is about twice as fast as func1, because func1 doesn't use RVO that Fruny was talking about. So do I have to write my functions in the forum of func2 to take advantage of this feature?


So about my current question?
[s] [/s]
I can see the fnords.
Quote:Original post by Extrarius
I'd just like to point out that while const IS meant for humans, it can actually help the compiler optimize as well. It shouldn't work that way, but there was code posted here on gamedev that showed (via the assembly ouput) that const made VS.Net 2003 optimize better.

It was for the vector class with members x,y,z,w that could also be accessed as [0] to [3]. The array used for [0] to [3] was only optimized away when it was made const, so without the const the compiler was leaving out a pretty big optimization (presumably because of aliasing issues).


its was a constant array of pointer to data member (not to be confused with pointer to member functions) its was also static member so there was only one instance.

If anyone is interested the original thread was here with the assembly output.

And the code that Extrarius mentioned was my adaptation of that technique into a vector & matrix class not only is it some real nice syntactic sugar its optimizied to, that is here.

This topic is closed to new replies.

Advertisement