user5059319
user5059319

Reputation:

Why temporary is created in the following example

Could you please explain (better in terms of standard) why temporary is created in the following example in line marked with comment?

class A
{
public:

    bool operator<(const A& rhs) const {return true;}

};

set<A> s;

int main()
{
    s.insert(A());
    set<A>::iterator pos;
    pos = s.begin();
    (A)*pos;              // why temporary created here?

    return 0;
}

Upvotes: 0

Views: 55

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283624

The result of every conversion to an object type is a temporary.

Beware that Microsoft Visual C++ is non-compliant to this rule, when the conversion is an identity conversion. I've reported a bug on Microsoft Connect which also shows the rules in the standard that require creation of a temporary:

The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.

(section 5.4 [expr.cast] of the Standard, the xvalue language was added in C++11 but the creation of a temporary in this case has always existed)

Upvotes: 1

Related Questions