Reputation: 179
Consider a code where a struct has a member variable bar
and a member reference variable that refers to bar
. For instance:
struct Foo{
double bar;
double &bar_ref=bar;
};
void receivesFoo(Foo cp_foo){
//&cp_foo.bar_ref is the same as &my_foo.bar_ref
}
int main(){
Foo my_foo;
receivesFoo(my_foo);
return 0;
}
The problem is that if you make a copy of a Foo
by, for example, passing it to a function, cp_foo.bar_ref
will refer to my_foo.bar
and not to cp_foo.bar
. How can I make it refer to cp_foo.bar
instead?
Note: I use these references variables for naming convenience, as some tutorials make it look like a possible use and I'd rather avoid all the readability issues associated with macros.
Upvotes: 1
Views: 61
Reputation: 179
One alternative would be to use the member initializer list of a copy constructor:
struct Foo{
double bar;
double &bar_ref;
Foo():bar_ref(bar){}
Foo(const Foo& a):bar_ref(bar){}
};
This seems to work, but adds an inconvenience of having to maintain two separate initialization lists with similar code. If you are allowed to use C++11 you can avoid it by doing:
struct Foo{
double bar;
double &bar_ref=bar;
Foo(){}
Foo(const Foo& a){}
};
Notice you may encounter similar issues if you use pointers
As @juanchopanza comments, you may also improve the previous example by using the default keyword. See this question for more details:
struct Foo{
double bar;
double &bar_ref=bar;
Foo()=default;
Foo(const Foo& a){}
};
Upvotes: 1