mardi 24 octobre 2017

Reference member initialized from a by-value constructor parameter

Under what conditions is this code correct:

struct A {
  A(B b) : b_(b) {}
 private:
  const B& b_;
}
B b_permanent;
A a(b_permanent);

IIUC, b will be a copy of b_permanent, and b_ will be bound to that copy. But what is the lifetime of b_? If it is only for the duration of the ctor, then this is wrong because b_ will be bound to an out-of-scope object by the time ctor finishes. And if that's the case, why is it even legal in C++, and doesn't even cause lint warnings?

OTOH, if b_ lifetime is extended to equal the lifetime of a, then can you link me to a rule that states that?

Does the answer depend on whether B is a fundamental or compound type?

Does the answer depend on C++ 11 vs 14 vs 17? (I'm not interested in anything before 11.)

Aucun commentaire:

Enregistrer un commentaire