passing an object by const& and by & to the same function

129 views Asked by At

I have an image function declared as

thresholding( const Image &imgSrc, Image &imgDest );

What happens if I do this;

Image img;
tresholding( img, img );

Is this well-defined? Because in this case img is changed.

P.S: threshold reads imgSrc and if `imgSrc[i] < lowerThr -> imgDest[i] = 255 else imgDest[i] = 0

And to be more precise:

__m128i _mm_src = _mm_load_si128 ( any_value );
__m128i _mm_src = _mm_load_si128 ( (__m128i*) &imgSrc[0] );
__m128i _mm_dest = _mm_load_si128 ( (__m128i*) &imgDest[0] );


_mm_dest = mm_cmpgt_epi16 (a, thr);
2

There are 2 answers

2
Columbo On BEST ANSWER

Having multiple references with possibly differing type to one object (just as having multiple pointers to the same object) is not problematic. The behavior of the function may be fine too: An expression like

imgDest[i] = (imgSrc[i] < lowerThr) * 255;

is well-defined for imgSrc and imgDest referring to the same object. No problems with sequencing o.s. occur. You should check the documentation or the source for threshold though, too be sure - It may be implemented in a way that requires imgSrc to be constant throughout execution. You shouldn't make assumptions without knowledge of the implementation.

0
AudioBubble On

Whether this is well-defined depends on the specification of the function. The language allows multiple references to the same object, even if some are const-qualified and others aren't, but many functions do not. Any modifications made through imgDest will immediately be visible through imgSrc, and many functions with parameters similar to yours assume that after modifications to imgDest, the original image is still available in imgSrc. If your function makes such an assumption, then it's easy to say that the language allows such a call, but that's like saying the language allows printf(NULL);: sure, technically it does, but if you also consider the specification of the function, that's still undefined.