简体   繁体   English

由于未初始化的成员,在构造函数案例崩溃之前调用的C ++函数

[英]C++ function called before constructor cases crash due to uninitialized members

I have this program 我有这个程序

#include <iostream>
#include <memory>

using namespace std;

class B {
public:
    void printB() {
        cout << __FUNCTION__ << endl;
        cout << mModuleName << endl;
    }
    void setModuleName() {
        mModuleName = "BBBBBBB";
    }

private:
    string mModuleName;
};

class A {
public:
    void printA() {
        cout << __FUNCTION__ << endl;
        b.printB();
    }
    B b;
};

int main(int argc, char ** argv) {
    cout << " START " << endl;

    std::shared_ptr<A> a;

    a->printA();

    a = std::make_shared<A>();

    cout << " END " << endl;
    return 0;
}

Here is the output: 这是输出:

vagrant@vagrant:~/development$ ./a.out
 START
printA
printB
Segmentation fault (core dumped)

This obviously crashes when reaching to line where he tries to access mModuleName. 当到达他尝试访问mModuleName的行时,这显然崩溃了。 I can fix it by moving printA() after make_shared line but I would like more robust solution to prevent SIGSEGV. 我可以通过在make_shared行后移动printA()来解决此问题,但是我想使用更强大的解决方案来防止SIGSEGV。 Any suggestions? 有什么建议么?

This isn't an actual problem, you're simply doing something that is obviously going to crash because you are dereferencing a null pointer. 这不是一个实际的问题,您只是在做显然会崩溃的事情,因为您取消引用了空指针。

You can do this as an alternative and call make_shared in the same line you declare the object. 您可以作为替代方法,并在声明对象的同一行中调用make_shared

int main(int argc, char ** argv) {
    std::shared_ptr<A> a = std::make_shared<A>();
    a->printA();
    return 0;
}

There is no real reason to split up the object declaration and initialization in this case. 在这种情况下,没有真正的理由拆分对象声明和初始化。

I can fix it by moving printA() after make_shared line but I would like more robust solution to prevent SIGSEGV. 我可以通过在make_shared行后移动printA()来解决此问题,但是我想使用更强大的解决方案来防止SIGSEGV。 Any suggestions? 有什么建议么?

One possible method is to use a non-member function. 一种可能的方法是使用非成员函数。

namespace MyApp
{
   void print(A* aptr)
   {
      if ( aptr != nullptr )
      {
         aptr->printA();
      }
   }
}

and in main use main用途

MyApp::print(a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM