指针成员变量在C ++类中初始化 [英] Pointer Member Variable Initialization in C++ Classes

查看:589
本文介绍了指针成员变量在C ++类中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来如此基本,以至于我认为我没有努力去自己找到答案,但我发现我搜索了大约20分钟,发现没有回答。

This is going to sound so basic as to make one think I made zero effort to find the answer myself, but I swear I did search for about 20 minutes and found no answer.

如果一个私有c ++类的成员变量(非静态)是一个指针,并且它不是在构造函数中初始化的(通过初始化列表或在构造函数中的赋值),它的值是什么时候类是完全实例化的?

If a private c++ class member variable (non-static) is a pointer, and it is NOT initialized in the constructor (either through an initialization list or an assignment in the constructor), what will its value be when the class is fully instantiated?

补充问题:如果上面的问题的答案是除NULL之外的任何东西,并且我希望始终将一个特定的成员指针变量初始化为NULL,并且我有多个构造函数,我真的必须为每个构造函数中我写的指针显式初始化?如果是这样,专业人员如何处理这个?当然没有人实际上为所有的构造函数中的同一个成员放置多余的初始化器,是吗?

Bonus question: If the answer to the above question is anything other than NULL, and I wish to always initialize a particular member pointer variable to NULL, and I have multiple constructors, do I really have to put an explicit initialization for that pointer in every constructor I write? And if so, how do the pros handle this? Surely nobody actually puts redundant initializers for the same member in all their constructors, do they?

编辑:我希望我可以选择两个答案在这里。 Bleep Bloop推荐的智能指针似乎是最优雅的方法,它得到了最多的投票。因为我没有在我的工作中使用智能指针(还),我选择了没有使用智能指针作为答案的最说明性的答案。

I wish I could've chosen two answers here. The smart pointers recommended by Bleep Bloop seem to be the elegantest approach, and it got the most up votes. But since I didn't actually use smart pointers in my work (yet), I chose the most illustrative answer that didn't use smart pointers as the answer.

推荐答案

你在正确地思考。如果你不初始化它,它可以是任何东西。

You're thinking correctly. If you don't initialise it, it could be anything.

因此,你的问题的答案还没有,初始化它的东西,或给它一个NULL nullptr,在最近的C ++标准)。

So the answer to your question is yet, either initialise it with something, or give it a NULL (or nullptr, in the most recent C++ standard).

class A
{
};


class B
{
private:
    A* a_;

public:
    B() : a_(NULL) { };
    B(a* a) : a_(a) { };
};

我们的默认ctor使它为NULL(替换为 nullptr 如果需要),第二个构造函数将用传递的值初始化它(这不能保证是好的)。

Our default ctor here makes it NULL (replace with nullptr if needed), the second constructor will initialise it with the value passed (which isn't guaranteed to be good either!).

这篇关于指针成员变量在C ++类中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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