14 ms·
In C++ it's quite easy to get burned by keeping a reference to something where the owner went out of scope eg. class Foo { int bar; int& getBar(
by rubber_duck 10y ago
In C++ it's quite easy to get burned by keeping a reference to something where the owner went out of scope eg.
class Foo {
int bar;
int& getBar() { return bar; }
}
if you take ref of bar and Foo goes out of scope well fuck. It gets even worse, eg. :
vector<int> foo;
int& bar = foo[i];
foo.push_back(1)
that last line can cause foo to reallocate the buffer and bar is then invalid, meanwhile that code will compile without warnings (well I'm guessing it will I haven't done C++ in a year :) )
- akie 10y agoThank you! That clarifies it quite a bit. My C/C++ is too rusty to remember these internals...
- saghm 10y ago> My C/C++ is too rusty Pun intended?
- satbyy 10y agoJust hit 'Run' here: http://rextester.com/BDGO47890 http://rextester.com/BDGO47890 You can see the program crash
- rubber_duck 10y agoNice, but the example crashes because you take a reference to uninitialized vector, if you initialize it and grow the vector I found that it will either keep "working fine" if you don't expect the data to change or randomly give garbage data - depending on compiler/stdlib - especially since the time when the buffer grows is implementation defined. Here is a better example : http://rextester.com/MAJDQ8375 http://rextester.com/MAJDQ8375 On VC++ it will return : Reference is 0 but value is 9 On clang it will return : Reference is 32579632 but value is 9 So let's say I wasn't mutating the 0 index, VC example would work fine at runtime and then clang would suddenly start giving garbage results. This has caused me week of debugging in a big code base.
- satbyy 10y agoThanks for the catch!