C++ constructor question
So we have this class "SimpleImage" that uses copy-on-write semantics. In a couple places in code, there is this:
SimpleImage safeCopy = SimpleImage(some3rdPartyHandle);
Now the thought is that this should take an image from a 3rd party library, and attach it to a temporary SimpleImage class. Then, upon construction of "safeCopy", we should get a unique copy because we can't reliably track reference count on images from 3rd parties. Point being, we want a unique copy of the image data.
This would work... if it created a temporary SimpleImage object! Instead it is exactly (and I checked the assembly - and this is in debug build!) the equivalent of writing
SimpleImage safeCopy(some3rdPartyHandle);
which only attaches it and we don't get our unique copy. It doesn't even bother to build our temporary object at all! We have to do this instead:
SimpleImage tempCopy(some3rdPartyHandle);
SimpleImage safeCopy(tempCopy);
or this will work too
SimpleImage safeCopy;
safeCopy = SimpleImage(some3rdPartyHandle);
My question though is why? This is in MSVC2008 - is this correct c++ or a mistake in the compiler? That is.. the fact that it skips making the temporary altogether even in debug build?
This goes into the same question. The gist of it is that
T x = a;
and
T x(a);
are mostly equivalent, except when used with explicit constructors, in which case only the latter succeeds.
T x = a;
and
T x(a);
are mostly equivalent, except when used with explicit constructors, in which case only the latter succeeds.
The first form also requires an accessible copy constructor (even though compilers should normally optimize away actual copying).
Quote:Original post by d00fus
This goes into the same question. The gist of it is that
T x = a;
and
T x(a);
are mostly equivalent, except when used with explicit constructors, in which case only the latter succeeds.
My point was that it turned out that
T x = T(a); // or T x(T(a));
and
T x(a);
were coming out to be the same. I had expected the first one to create a temporary T, and it didn't.
Quote:Original post by jwezorek
Can't you just make a function that returns the copy?
Yup - but I was curious about the not-creating-a-temporary thing just in case it ever matters again in the future.
If your copy constructors have normal semantics (not called for side-effects), then it should never matter if they are actually called or not.
With GCC you can force it to not optimize away those copies with -fno-elide-constructors. No idea how to achieve it with VC++.
With GCC you can force it to not optimize away those copies with -fno-elide-constructors. No idea how to achieve it with VC++.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement