Reputation:
Anyone knows how to initialize a reference in a dynamically allocated structure? or why this doesnt work?
#include <stdio.h>
#include <stdlib.h>
class A
{
};
struct S
{
A& a;
};
int main()
{
A a;
S* s=new S;
s->a=a;
printf("a addr:%p\n", &a);
printf("s->a addr:%p\n", &(s->a));
delete s;
return 0;
}
output:
a addr:0x7fff95b65aaf
s->a addr:(nil)
Upvotes: 3
Views: 569
Reputation: 320699
It doesn't work because you are trying to assign something to a reference member (which, of course, does not affect the reference itself, but rather the referenced object). You are not initializing the reference in your code. References can only be initialized at the very moment they are "born", their initialization cannot be postponed for later.
When you do new S
, you are asking the compiler to use the compiler-generated default constructor for S
. The default constructor for S
cannot be generated, since the compiler does not know how to initialize reference member a
. References in C++ cannot be left uninitialized, they cannot be default-initialized, and they value-initialized. Specific initializer always has to be supplied explicitly.
Unfortunately in C++89/C++03 there's no way to do that for a dynamically allocated struct S
(as defined in your code). You have to provide your own constructor for this.
In C++11 you can use uniform initailization syntax
S *s = new S { a };
which will attach the S::a
member of newly allocated object to a
.
Upvotes: 2
Reputation: 12268
You need to initialize reference members within the initializer list of a constructor. Even the body of the constructor is too late, because the member has already been initialized, and can't be changed.
In your code, you are using the (compiler-provided) default constructor, and then trying to set the reference after the object has been constructed.
Try this:
struct S
{
S(A& a_) : a(a_){}
A& a;
};
int main()
{
A a;
S* s=new S(a);
...
Upvotes: 3