iranano 0 Newbie Poster

In the follwong program a class-type temporary is cast to a refrence and they changed:

struct A 
{
    int a;
    A() { a = 100; }
};
void f(A& x) { x.a = 200; };
int main()
{
    f((A&)A{});
}

No errors in Visual Studio and GCC. But is it safe to use such cast, instead of useing rvalue reference, in Standard C++?

Dani AI

Generated

Short answer: don’t do that. Casting a prvalue temporary to a non‑const lvalue reference (the trick shown in the original post) is a brittle workaround that relies on subtle wording about materialization and lifetime; compilers may accept it, but the Standard does not bless it as a safe, portable pattern. See the language on reference initialization and temporary materialization for the rules that matter. (reference initialization, temporary materialization).

Why it’s risky: an explicit cast can produce a glvalue that refers to the temporary, and that temporary lives only until the end of the full expression that created it. That means mutations through the casted reference will usually “work” during the called function, but the code depends on very specific lifetime/initialization rules and can easily become undefined in other contexts (or when combined with constness, overloads, return-by-reference, or aggressive optimizations). (reference initialization)

Safer alternatives (pick one depending on intent):

struct A { int a = 100; };

void f(A&& x) { x.a = 200; }   // intended for temporaries
f(A{});                       // binds to prvalue safely

or

void f(A x) { x.a = 200; }    // pass-by-value: operates on a copy; return it if caller needs changes

If the goal is to modify a caller-owned object, pass an lvalue (no cast). Never rely on casting away const to make a temporary writable — const_cast/reinterpret casts that modify an actually-const object result in undefined behavior. (const_cast notes)

Recommendation: change the API to express intent—accept an rvalue reference or take by value—rather than silencing the type system with a cast. This is clearer, portable, and guaranteed by the Standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.