Re: const correct member variable access thru function?
patrik.kahari@googlemail.com wrote:
I want to implement what should be a very simple feature.
Say, I want to log every time the member variable x_ is used (or say i
want lazy initialization of the variable), then i need to restrict
access to the variable thru a function. I do this by making x a
function returning a reference to the x_ variable.
Example code:
// I want to emulate the behaviour of this struct
struct A{
public:
int x_;
};
[..]
The proper way to do it (IMO) would be to use a proxy class that would
know whether it's on the right or on the left side of the assignment op.
It's not as simple as introducing two overloaded functions, like here:
struct A {
int x() const { return x_; }
int& x() { return x_; }
private:
int x_;
};
because in this case if 'A' is non-const, then the non-const version
will be called if you use it in an expression (even though you're not
trying to assign to it):
A a;
a.x() = 42;
int b = a.x(); // here non-const A::x() is called
IIRC, over the years several solutions have been discussed here and
in c.l.c++, you could try finding them on Google Groups (or hope that
somebody remembers and helps you by supplying the link[s]).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]