15 ms·
Nope. You can only take a reference to an lvalue, which is (essentially) an expression that is legal to use in the form `my_lvalue = .... Otherwise, there's not
by gowld 6y ago
Nope. You can only take a reference to an lvalue, which is (essentially) an expression that is legal to use in the form `my_lvalue = ....
Otherwise, there's nothing to take the reference of.
int* ref1() { return &1; }
-> error: lvalue required as unary '&' operand
//
#include <stdlib.h>
int alloc() {
return *(int*)malloc(sizeof(int));
}
int* ref() { return &alloc(); }
-> error: lvalue required as unary '&' operand
You can still be unsafe though, by making a reference to a stack-allocated object and letting it go out of scope :
int* make_unsafe_ref() { int a; return &a; }
-> warning: function returns address of local variable
- masklinn 6y ago> You can only take a reference to an lvalue, which is (essentially) an expression that is legal to use in the form `my_lvalue = …. I mean it could implicitly allocate, that's what Rust does for instance. Your second and third attempts would not compile though, the first would by returning a `&'static T`.
- steveklabnik 6y ago"implicitly allocate" is slightly misleading, imho. It's promoted to a static. There's no malloc involved.
- masklinn 6y ago> "implicitly allocate" is slightly misleading Maybe. I just meant that storage is created implicitly (static or stackframe depending on the case), then a reference is created to that.,
- steveklabnik 6y agoTotally, I don't think you're wrong, just like, people read "allocate" in different ways. I wish words were clearer, heh.