初始化引用 - 警告C4355:'this':用于基本成员初始化程序列表 [英] Initialize a reference - warning C4355: 'this' : used in base member initializer list

查看:609
本文介绍了初始化引用 - 警告C4355:'this':用于基本成员初始化程序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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() {
}

目前,我尝试初始化B中的引用,我使用方法1.但是,方法1将标记我的警告,这是可以理解的。

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.

因此,我必须回退使用方法2,通过使用动态内存分配。

Hence, I have to fall back using Method 2, by using dynamic memory allocation.

有没有更好的方式,我可以使用,而不需要手动内存分配/ dellocation(确定,我知道智能指针)

Is there any better way I can use, without the need of manual memory allocation/ dellocation (OK. I know smart pointer)?

我更喜欢方法1,只是我对警告不舒服。

I prefer Method 1, just that I am not comfortable with the warning.

推荐答案

注意这是一个警告(所以这是危险的,不是非法的)。

Note this is a warning (so it is dangerous not illegal).

编译器担心的是,对象尚未完全初始化。因此,如果指针在B类构造函数中使用,你将处于未定义的行为。

What the compiler is worried about is that you are passing a pointer for an object that has not been fully initialized. Thus if the pointer is used in the B class constructor you are in undefined behavior.

所以如果你使用这个,你可以做的唯一的事情是将指针成员变量(引用或指针)。 但是注意注意对变量的分配,因为你可以调用一个隐式转换(我不知道这是否实际上是一个问题,但RTTI不可用,直到对象完全形成)。

So if you do use this the only thing you can do is assign the pointer to a member variable (reference or pointer). But note be careful of the assignment to a variable as you may invoke an implicit cast (I am not sure if that is actually a problem but the RTTI is not available until the object is fully formed).

您通过存储引用要实现什么?

What are you trying to achieve by storing the reference?

这篇关于初始化引用 - 警告C4355:'this':用于基本成员初始化程序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆