I have the following problem:
I have a class which should do this:
Obj o;
Obj o1(o), o1=o; // deep-copies
const Obj c(o), c=o; // deep-copies
const Obj c1(c), c1=c; // shallow-copies
Obj o2(c), o2=c; // deep-copies
How can I do this preferably without inheritance? (I mean I would do Const_obj
inheriting from Obj
otherwise.)
EDIT:
Using o.clone()
directly is not an option because then I could easily introduce bugs by accidentally not cloning.
EDIT:
Finally, there is a proper, complete solution with lazy evaluation using the idea from Effective C++ by Scott Meyers. Check out my answer below.
You can, in part, with a dummy argument:
EDIT: A clone-only approach could be what you want (together with move semantics the performance hit might not be too large):
No, you can't.
Also, if it was possible, I would find it really confusing. Just make methods that suit your needs, and name them in an unambiguous way.
After reading Effective C++ by Scott Meyers, the following is a solution:
define a template which does a lazy evaluation (with reference counting):
and the lazy stores the Obj_data privately, has protected accessors, one for modification, one for read-only access.
The modifier accessor first deep-copies the
Obj_data
if necessary, then hands over the reference to the data. The read-only accessor just returns a const reference.The overall cost of this is storing 2 extra pointers (one for the data and one for the counter) and a counter.
Implementation is something like this:
So, reading and modifying an attribute of
Obj
goesNote that you can only use
data()
in aconst
member asmod_data()
is a non-const function in the class, so this solution is completely safe with little overhead.Theory background: the desired behaviour in the question is an implementation detail, does not concern the client. Therefore we solve it by private inheritance.