Boost logo

Boost :

From: Rani Sharoni (rani_sharoni_at_[hidden])
Date: 2004-02-10 07:11:18

Raoul Gough wrote:
> "Rani Sharoni" <rani_sharoni_at_[hidden]> writes:
> [snip]
>> The fact that the additional temporary is const might,
>> theoretically, encourage the optimizer to generate faster code but
>> AFAIK no C++ optimizer is actually aware about the existence of C++
>> const and practically *ignore* it.
> So I can't cast away const on the reference, because it might be bound
> to a const copy of the rvalue (leading to undefined behaviour)?

That's right. You can work around this theoretical pitfall using mutable
members if needed.

> BTW, couldn't the optimizer (after verifying that the const & is never
> const-casted) perform the same optimizations anyway?

I had aliasing optimizations in mind:

struct X { bool flag; };

X source();

void DoSomething(X const&);

void foo()
    X const& r = source();

    if (r.flag) { /* #1 */ }


    if (r.flag) { /* #2 */ }

In case that the optimizer is C++ const aware then it can consider the
temporary as being const (after wisely eliminating the additional fake copy
to const temporary).
Now since r refers to const object the optimizer is free to think that the
value of it will not change after calling DoSomething (i.e. potential
aliasing issue). Such aliasing issues might seem insignificant yet AFAIK
this is what makes FORTRAN much faster than C (i.e. assuming no aliasing).

> class nc {
> nc (nc const &) { }
> public:
> nc () { }
> nc const &by_ref () const { return *this; }
> };
> struct nc_derived : nc { };
> void bar (nc const &);
> void foo (bool b) {
> bar (b ? nc() : nc_derived()); // Ill-formed (8.5.3)
> bar ((b ? nc() : nc_derived()).by_ref()); // OK AFAIK
> }
> Both VC++ and g++ report that the nc copy constructor is inaccessible
> on both of the bar calls. I don't see how the compiler is allowed to
> introduce a copy in the second one (with the member function call).
> Comeau online 4.3.3 diagnoses the error on the ill-formed line and
> accepts the second one.

This is dark C++ corner:


Boost list run by bdawes at, gregod at, cpdaniel at, john at