My c++ is rusty, so while trying to improve some code I wrote a few days ago by changing some calls from passing a MyClass *const thing
to Myclass& thing
, I noticed that nothing complained about code that followed this contrived example.
#include <iostream>
class Foo {
public:
Foo() {
std::cout << "foo created" << std::endl;
}
~Foo() {
std::cout << "foo destroyed" << std::endl;
}
Foo(Foo& other) {
member = other.member;
std::cout << "foo copied" << std::endl;
}
bool member = false;
};
class Bar {
public:
Bar(Foo& foo) :foo_(foo) { }
Foo foo_; // **** HERE IS THE BUG this should be: Foo& foo_;
};
int main() {
Foo foo;
Bar barOne(foo);
Bar barTwo(foo);
foo.member = true;
std::cout << barOne.foo_.member << std::endl;
std::cout << barTwo.foo_.member << std::endl;
}
I really wanted to have one Foo object, but since I forgot the &
I got three instead.
foo created
foo copied
foo copied
0
0
foo destroyed
foo destroyed
foo destroyed
adding the &
I get the right result.
foo created
1
1
foo destroyed
Note: the Foo, constructors and destructor are just there to demonstrate what's happening.
I know is legal, but is there a compiler flag that would warn you if you declare an Object as a member variable? Is it a bad practice to store a reference in a member variable? I would not think it is, but like I said my c++ is rusty to say the least.
Update
To answer the question of what I was refactoring from. I was doing something similar to this. I was refactoring to references as everything I read about modern c++ says to prefer references rather than pointers.
class Bar {
public:
Bar(Foo const* foo) :foo_(foo) { }
Foo const* foo_;
};
int main() {
Foo foo;
Bar barOne(&foo);
Bar barTwo(&foo);
foo.member = true;
std::cout << barOne.foo_->member << std::endl;
std::cout << barTwo.foo_->member << std::endl;
}