C ++如何避免访问尚未初始化的对象的成员 [英] C++ How to avoid access of members, of a object that was not yet initialized

查看:78
本文介绍了C ++如何避免访问尚未初始化的对象的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在程序中传递对象的最佳做法是什么,避免访问未初始化的成员变量。

What are good practice options for passing around objects in a program, avoiding accessing non initialized member variables.

我写了一个小例子,我认为它很好地解释了问题。

I wrote a small example which I think explains the problem very well.

#include <vector>
using namespace std;

class container{public:container(){}

    vector<int> LongList;
    bool otherInfo;
};

class Ship
{
public:Ship(){}

    container* pContainer;
};

int main()
{
    //Create contianer on ship1
    Ship ship1;
    ship1.pContainer = new container;
    ship1.pContainer->LongList.push_back(33);
    ship1.pContainer->otherInfo = true;

    Ship ship2;

    //Transfer container from ship1 onto ship2
    ship2.pContainer = ship1.pContainer;
    ship1.pContainer = 0;

    //2000 lines of code further...
    //embedded in 100 if statements....
    bool info = ship1.pContainer->otherInfo;
    //and the program crashes

    return 0;
}


推荐答案

编译器无法确定您是否正在介绍 未定义的行为 ,如您的示例所示。因此,除了用特殊值 初始化指针变量外,没有其他方法可以确定指针变量是否已初始化。

The compiler cannot determine if you are introducing undefined behavior like shown in your example. So there's no way to determine if the pointer variable was initialized or not, other than initializing it with a "special value".


在程序中传递对象,避免访问未初始化的成员变量的良好实践方法是什么。

What are good practice options for passing around objects in a program, avoiding accessing non initialized member variables.

最好惯例总是初始化指针,并在取消引用之前进行检查:

The best practice is always to initialize the pointer, and check before dereferencing it:

class Ship {
public:
    Ship() : pContainer(nullptr) {}             
        // ^^^^^^^^^^^^^^^^^^^^^ 
    container* pContainer;
};

// ...

if(ship1.pContainer->LongList) {
    ship1.pContainer->LongList.push_back(33);
}






至于您的评论


所以没有可以警告我的编译器标志?

So there are no compiler flags that could warn me?

在更简单和明显的情况下,编译器可能会警告您:

There are more simple and obvious cases, where the compiler may leave you with a warning:

int i;
std::cout << i << std::endl;

吐出

main.cpp: In functin 'int main()':
main.cpp:5:18: warning: 'i' is used uninitialized in this function [-Wuninitialized]
     std::cout << i << std::endl;
                  ^

请参见实时演示

这篇关于C ++如何避免访问尚未初始化的对象的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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