I think that this is valid code in MSVC:
MyClass* pMc = &MyClass();
However, when I try to do the same thing with primitive data-types I’m getting a compilation error.
int* pInt = &int();
Error:
error C2101: '&' on constant
I have 3 questions:
- Why does
int()give me a constant? - Why does error C2101 exists in the first place? what’s wrong with getting the address of a constant?
- Is there a way I could declare int (or other primitive) references that point to temporary objects? (that is, without creating a local variable first)
About the 3rd question:
I do not want to do something like this:
int i = int();
int* pInt = &i;
If I’m working with references to local objects (the reasons why are irrelevant), I don’t want to have to declare each and every object twice. It’s tedious, annoying and the names would be really confusing.
I don’t know the answer to 1 (I think the error is wrong, because I’m pretty sure
int()is not a constant), but(2) Taking the address of a temporary is illegal. Your code shouldn’t compile but it does because of a nonstandard MSVC++ extension.
(3) Yes, use rvalue-references or const lvalue-references:
The lifetime of the temporary will be prolonged until the reference goes out of scope.
However, I hope you have a good reason for using one of the two above rather than