Home > front end >  Assigning a reference to a struct
Assigning a reference to a struct

Time:11-06

I have a variable ntot_sols who's final value isn't known when my object is constructed.

Consequentially I want to store a reference to the variable instead of the value since it's subject to change.

I think the following code will do it.

struct ItemWeighter {
   int nsols;
   int ntot_sols;

   ItemWeighter(int _nsols, int& _ntot_sols) {
     nsols = nsols;
     ntot_sols = _ntot_sols;
   }
   
   float weight() {
      return nsols / float(ntot_sols);
   }
};

But I'm surprised that ntot_sols is type int and not int &. How does the variable know that it's a reference?

CodePudding user response:

You can't use the assignment operator to bind a reference. It has to be bound when first created. For a class member variable, this means you have to do it in a member initializer list; the body of the constructor is too late.

Example:

#include <iostream>


class foo {
private:
    int& x;
public:
    foo(int& other_var) : x(other_var) { }
    ~foo() { }
    void print_x() { std::cout << x << std::endl; }
};

int main() {
    int a = 5;
    foo my_foo(a);
    my_foo.print_x();
    a = 10;
    my_foo.print_x();
    return 0;
}

Try on godbolt. It prints out:

5 
10

Note that such code, where your object holds a reference to another variable created elsewhere, can be risky. It is up to you to make sure that the referenced int has a lifetime at least as long as the foo object. It can be easy to get this wrong, and the compiler won't help you. Consider for instance:

foo make_a_foo() {
    int a = 7;
    foo f(a);
    return f;
}

void other_func() {
    foo g = make_a_foo();
    g.print_x(); // undefined behavior!
}

Here g.x is a reference to the local variable a from make_a_foo(), whose lifetime ended when make_a_foo() returned.

It may be better after all to make x an ordinary int member variable, instead of a reference, and call a setter function to update its value when needed.

  • Related