Returning a big object

just say NO


A bad example

IMAGE read_new_image_format(const char * file_name) { figure_out_image_dim(); IMAGE ret_image(no_rows,no_cols,depth); fill_in(ret_image); return ret_image; } .... IMAGE loaded_image = read_new_image_format("image_file.xbmp");


In contrast, a Lazy Image builds the loaded_image right in its place:
an IMAGE constructor is called only once



When read_new_image_format("image_file.xbmp") is called, it creates a ret_image, fills it in, copies it onto stack as the return value, and destroys ret_image. The return value from read_new_image_format(), an IMAGE, is then copied over to a loaded_image (via a copy constructor). After that, the return value on stack is destroyed. Thus image constructors are called 3 times, and the destructor 2 times. For big images, it may be very expensive to construct/copy/destroy objects, especially over again. Some optimized compilers can cut down on one copying/destroying; still it leaves at least two calls to a constructor. LazyImages (aka promises) (see below) can construct IMAGE loaded_image in place, with only a single call to a constructor.



Next | Table of contents