I will give the first person to correctly explain why this compiles a nice compliment

#include <iostream>

class A {};

int main() {
std::cout << &(A() = a) << "\n";
}
Follow

Oops there is missing declaration of the variable a. This is what you should be examining:

class A {};

int main() {
A a;
std::cout << &(A() = a) << "\n";
}

@wallhackio Maybe it's stripping out <iostream> because it thinks that it's a HTML tag that it doesn't recognize?

@wallhackio OK, if the a is declared, then I think that A() is creating a new object of class A, and then = a copies the values from a into it, and, like any assignment, returns its right part, so returns a, and & will simply return the address of a.

But I'm too stupid for C++, I'm probably wrong

@vaporeon_ @wallhackio this is very close but there is some pedantry here

  • strictly, the behavior of (non-overridden) assignments (yes you can override assignment in this language) is that the value of the left side (after assignment) is the value of the assignment expurression. this matters because of potential type coercion shit
  • the default behavior of an assignment is guaranteed to return an lvalue, this is why you can create an lvalue refurence (which is what &) out of the result of the expurression. (no i do not even know how to begin to explain what an lvalue refurence “is”)

@aescling @wallhackio > the value of the left side (after assignment) is the value of the assignment expurression

Oh... So will &(A() = a), instead of returning the address of a, return the address of the newly-created A()?

@vaporeon_ @aescling but the result of A() is an rvalue, which is not allowed to be given to & or appear on the left side of an assignment. That is the mystifying part here

@wallhackio it's just outputting the address of a temporary object? and then a newline? why wouldn't it compile? there's not even any UB here i think (since you never dereference the resulting pointer)

@alyssa a constructor returns an rvalue which is not supposed to be allowed to appear on the left side of an assignment

@wallhackio at least in C++23 it returns a prvalue, which can be implicitly converted to an xvalue. although, hmm, an xvalue is only a glvalue, not an lvalue (which the assignment operator requires) so that doesn't seem to explain it. alas idk

Sign in to participate in the conversation
📟🐱 GlitchCat

A small, community‐oriented Mastodon‐compatible Fediverse (GlitchSoc) instance managed as a joint venture between the cat and KIBI families.