On 18 Nov 2015 21:08:04 GMT
I do not know what 'foo->bar->baz = 1' refers to, as I have not seen
your Foo class definition (have I missed a post somewhere? - if so my
apologies). You said '"const Foo* foo" just means "I can't use 'foo'
to modify anything"'. I took from this (and from the posting to which
you were replying) that this was intended as a general statement about
the qualities of 'const', rather than about a particular Foo class
definition which I have not seen. Saying that foo cannot modify
anything is a statement that it is pure. Taken on that basis, what you
said was wrong. This is valid code, but it modifies 'a', 'b', and the
state of the output stream:
#include <iostream>
int a = 0;
struct Foo {
static int b;
int do_it1() const {++a; std::cout << a << '\n'; return a;}
int do_it2() const {++b; std::cout << b << '\n'; return b;}
};
int Foo::b = 0;
int main () {
const Foo* foo = new Foo;
foo->do_it1();
foo->do_it2();
delete foo;
}
> (I simplified by ignoring the case where you can const_cast foo,
> because it's a very rare thing to do.)
>
> > (Or to be more exact, it means "I can't use foo to
> > modify any non-mutable data of the object foo points to", but I
> > don't want to confuse the basic point that const does not mean pure,
> > irrespective of whether there is any mutable object data around.)
> > "const" does not mean "no side effects".
>
> I don't know what "pure" means either, to be honest,
It refers to the absence of side effects. It requires amongst other
things that a function only depend on its arguments (in particular, not
on mutable state), and that the same input value(s) should always
produce the same return value. No function returning void could be
pure, because otherwise it would not do anything. It enables many
compiler optimizations, including lazy evaluation, common subexpression
elimination and memoization, and (because it doesn't silently change
program state) makes programs easier to reason about and facilitates
safe concurrency - all pure functions are by definition thread safe).
D has a 'pure' keyword, for example. I think all constexpr functions
must in fact be pure (I must look that up some time), but there are
many pure functions which are not constexpr.
This is not to be confused with gcc's C function 'const' attribute,
which does require purity.
Chris