重置后是否使用了shared_ptr不确定的行为?

佐佐

我有这个测试程序:

#include <iostream>
#include <memory>

class A {
public:
    A()
    {
        std::cout<<"A Constructor\n";
    }

    ~A(){
        std::cout<<"A Destructor\n";
    }

    void show()
    {
        std::cout<<"A::show()"<<'\n';
    }
};

int main()
{
    auto p1 = std::make_shared<A>();
    // Relinquishes ownership of p1 on the object
    // and pointer becomes NULL
    p1.reset();
    std::cout<<p1.get()<<'\n';
    std::cout<<p1.use_count()<<'\n';
    p1->show();
    return 0;
}

产生以下输出:

A Constructor
A Destructor
0
0
A::show()

我通过gdb运行它,看到了:

:
:
(gdb) s
A::show (this=0x0) at so.cpp:18
18              std::cout<<"A::show()"<<'\n';
(gdb) s
A::show()
:

该行A::show (this=0x0) at so.cpp:18表示基础资源为空。我看了另一个问题,但那里使用了原始指针来调用成员函数。这种情况与该问题是否太相似,因为它p1->show()也应该等同于p1.get()->show();我的理解正确吗?

来自莫斯科的弗拉德

只需将数据成员添加到类中,就可以看到视觉上未定义的行为。

#include <iostream>
#include <memory>

class A {
public:
    A()
    {
        std::cout<<"A Constructor\n";
    }

    ~A(){
        std::cout<<"A Destructor\n";
    }

    void show()
    {
        std::cout<<"A::show()"<<'\n';
        ++x;
    }

    int x = 0;
};

int main()
{
    std::shared_ptr<A> p1(new A);
    // Relinquishes ownership of p1 on the object
    // and pointer becomes NULL
    p1.reset();
    std::cout<<p1.get()<<'\n';
    std::cout<<p1.use_count()<<'\n';
    p1->show();
    return 0;
}

例如在运行时这样的错误

Runtime error #stdin #stdout 0s 4280KB

可以显示。

那就是使用空指针访问数据成员。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章