since your foo is uninitialized you can initialize your foo with a size at least 1 before bar by using the initializer list. this is also c++98 valid.
struct C{
std::vector<int> foo;
const int &bar;
C();
};
C::C() : foo(1) // initialize foo with size 1
, bar(foo[0]) {
foo[0]=5; // this is guarateed to be exception safe
}
but you have to pay attention to the initializer list order. it is ordered by the order of declaration in the struct/class. see here
According to ISO/IEC 14882:2003(E) section 12.6.2:
Initialization shall proceed in the following order:
- First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list.
- Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
- Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
- Finally, the body of the constructor is executed.
edit:
thanks to Kerrek SB's comment, you can't use your vector. while you push something foo will be resized (reallocated) and bar will lose the right reference. you could either use a std::deque
or init the vector to a specific size that never will be passed.