Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!samsung!olivea!uunet!mcsun!hp4nl!duteca4!cornet From: cornet@duteca (Jan-Pieter Cornet) Newsgroups: comp.lang.c++ Subject: Returning class containing pointer members Summary: C++ needs optimization about subject Keywords: optimization, pointers Message-ID: <1289@duteca4.UUCP> Date: 22 Apr 91 23:55:11 GMT Reply-To: cornet@duteca.et.tudelft.nl Organization: Delft University of Technology, Dep. of Electrotechnical engineering. Lines: 63 When debugging a program I wrote as an excercise to learn C++, I came across something that is not a big hole in the language, but rather a slight inefficiency. I've implemented a class to perform large precision fractional arithmetic. The class looks something like this: class bigfloat { public: bigfloat(void); ~bigfloat(void); bigfloat& operator=(const bigfloat&); // any functions needed to handle bigfloats protected: char* data; int size; } Now consider a function returning a plain bigfloat; not a reference or pointer to a bigfloat. The inefficiency I noted -- which is, as far as I can see, part of the language definition -- is that when returning the value, first the data part of the local variable is copied to a newly allocated location, and immediately afterwards deleted. (It is copied to a newly allocated location because operator=() deletes any old data in my implementation). It would be better to just change the data pointer to the new data block and then not delete this data, but the functionality that controls this is divided between two functions ( operator=() and ~bigfloat() ) so it is hard to achieve this. I can probably figure out how -- using reference counts and such -- so don't mail me with patches that describe this fix. I just don't like all the hacks needed to accomplish such a simple task. Considering the above scheme of data copying and subsequent deletion to happen quite often, it may be wise to define a new constructor and a new assignment operator that the compiler can choose to call implicitly in these situations. The prototypes of these functions might look like (in the context of the above example): bigfloat::bigfloat(delete bigfloat&); // construct *this and delete arg ~~~~~~ bigfloat& bigfloat::operator=(delete bigfloat&); // copy and delete arg ~~~~~~ These functions will provide the interface to the programmer whenever a copy-with-delete is needed. The constructor will then be called whenever the function return value is used as a temporary in further calculations; the assignment operator is used in case the value returned is assigned to an already-allocated variable. When these functions default to the obvious combination of the original function and delete, no existing code is broken so compatibility is guaranteed. -- Jan-Pieter Cornet cornet@duteca.et.tudelft.nl P.S. Does anybody know why @ $ and ` are banned from the C world ??