初始化引用

编程入门 行业动态 更新时间:2024-10-13 02:13:30
本文介绍了初始化引用 - 警告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?

更多推荐

初始化引用

本文发布于:2023-10-26 07:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529439.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!