Skip to content

Mmmm... C++

Friday, 17 June 2005  |  cristian tibirna

(This entry is, of course, in relation to logs by ruurd, ruurd and mpyne)

I find it troubling that after so many years, C++ still needs such detailed explanations about fundamental functionality. If this situation would have taken a few short years, we could have suspected slow social evolution from old (functional languages) to new (OOP) paradigms. But persistence, at the scale we see, seem to rather signal problems with the language itself. The current discussion is just a small sand grain falling in the timeglass that measures the evolution of my personal relationship with C++, from 100% love (1993-4) to fifty/fifty love/hate (2003-4).

My personal opinion is that cctor and op= definition necessity is one of those subtle oddities of the language that grow to irk one's confidence in its tools (in the matter, C++), with the growing of experience. You have to grant it, coding cctor and op= over and over again, a few tens of times per week, becomes irky after 10 years.

ruurd and mpyne showed off the peculiarity of the relationships between the two constructs, using a similar situation as a frame for both (new creation of an object). It is a duty, IMHO, to underline that the op= is essential in all other (other than new creation) situations. This is the fundamental reason of its existence: carbon copying to already existing objects. This is why cctor only wouldn't be enough.

I tend to agree that the language should impose a bit more intelligence on the compilers and require an equivalence of actions between cctor and op=. I didn't yet encounter a situation where different behaviors be required from the two notions. Counterexamples more than welcome.

But from this positioning derives a warning too. Given that the compilers aren't required to ensure equivalence, it is your sacred duty to fulfill this requirement. Thus, advice no. 1: make very sure, always, that equivalent operations are perfomed on the call of any of the two operators and that the result is identical (i.e. a copy-constructed object or an assigned object would look the same).

The second advice is an amendment to Coplien's rule of Big Four. Advice no. 2: make sure to reflect thoroughly at the necessity of providing your class with a cctor and an op=. Act conservatively with respect to this reflection. It is very well known that the compiler provides some default ctor, cctor, op= and dtor if none manually defined. But it is quite often required that an object not be able to become into existence by copy-construction and, similarly, it might be necessary that no assignation be possible to the said object. In case you don't want cctor and/or op= (not even the default ones), it is enough to declare them private and forget to define (implement) them. This will give you nice compile-time errors if you ever try to copy-construct or assign-to such objects.

Again, fundamental knowledge...