Soft question: is struct field never read actually a code smell?

Consider the following:

pub struct Foo {
  x: Rc<Blah>
}

Now, if the x field is never read, we will get a warning.

===

Now, I have this use case as follows:

pub struct Manager {
  parts: Vec<Weak<Blah>>
}

pub struct Foo {
  x: Rc<Blah>
}

impl Foo {
  pub fn new(m: &mut Manager) -> Foo 
    let x: Rc<Blah> = ...;
    m.parts.push(Rc::downgrade(x));
    Foo { x }
  }
}

So here what is happening:

  1. there is some other 'manager' that has a bunch of Weak<Blah> and runs some code on them for every iteration

  2. the sole job of the Foo.x is to just keep the object alive, while the Foo is alive

Question: is this 'design pattern' described above (1) a code smell or (2) reasonable ? If (1), what should I be using instead ?

If you are holding the field for its destructor, then it is not a code smell. It's read in the destructor, but the warning doesn't count that.

3 Likes

This is precisely the use case. I have a toy GUi library. In this library, we have a struct Button; this struct needs to hold on to certain OpenGL resources while the Button is alive.

When I am holding onto something just for it's destructor, I usually name the field starting with an underscore, most often _handle.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.