1

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.

Ziezi
  • 6,375
  • 3
  • 39
  • 49
guivenca
  • 159
  • 1
  • 11

1 Answers1

1

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){}
};
Community
  • 1
  • 1
guivenca
  • 159
  • 1
  • 11
  • 2
    Maybe `Foo() = default;` would be more appropriate in the second example. It doesn't mess up value initialization of `bar`. – juanchopanza Oct 07 '15 at 06:08
  • @juanchopanza , That's new to me. I've edited the post, please check if it's correct and complete now. Thanks. – guivenca Oct 07 '15 at 06:55