|
|
|
|
|
by gowld
1892 days 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
|
|
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`.