class A;
class B {
public:
B(A& a) : a(a) {}
private:
A& a;
};
/* Method 1 */
/* warning C4355: 'this' : used in base member initializer list */
/*
class A {
public:
A() : b(*this) {}
private:
B b;
};
*/
/* Method 2 */
/* But I need to manually perform memory dellocation. */
class A {
public:
A() { b = new B(*this); }
~A() { delete b; }
private:
B* b;
};
int main() {
}
Currently, when I try to initialize the reference in B, I am using Method 1. However, Method 1 will flag me warning which is understandable.
Hence, I have to fall back using Method 2, by using dynamic memory allocation.
Is there any better way I can use, without the need of manual memory allocation/ dellocation (OK. I know smart pointer)?
I prefer Method 1, just that I am not comfortable with the warning.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…