没有初始化,shared_ptr如何在C ++中工作

0 c++ shared-ptr c++11

我正在经历shared_ptr并遇到了这个问题。

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { cout << "In fun... " << endl; }
};
int main()
{
    shared_ptr<A> a;
    a->fun();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是-有趣的是...

我想了解这是如何给上面的输出。

在进一步的实验中,如果存在成员变量并在该函数中使用它,则会抛出SIGSEGV。

class A
{
    public:
        A() { cout << "In constructor" << endl; }
        ~A() { cout << "Destructor" << endl; }
        void fun() { a = 5 ; cout << "In fun... " << endl; }
        int a;
};

int main()
{
    // A::fun();
    shared_ptr<A> a;
    a->fun();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的SIGSEGV抛出指针为空。

Vla*_*cow 6

两种情况下的代码都有未定义的行为,因为该指针的原始指针由shared_ptr初始化nullptr

在第二种情况下的代码试图将数据成员的存取存储器a使用nullptr

在第一种情况下,仅由于没有访问对象内存的权限而执行的代码没有失败。但是,该代码具有未定义的行为,因为您不能使用空指针来访问类的非静态成员。