c++ - 共享指针无需分配即可工作

标签 c++ c++11 shared-ptr

共享指针无需为 Win 类分配内存即可工作。

代码:

class Win
{
public:
    void disp()
    {
        //Do something
    }
};

int main()
{
    std::shared_ptr<Win> sharedptr;///holds null pointer
    sharedptr->disp();//// why its working
}

为什么它调用上面的函数而不为其分配内存。有人可以帮我解决这个问题吗?

最佳答案

尝试这样做:

#include <memory>
#include <iostream>
class Win
{
    public:
 void disp(){std::cout << x;}
 int x=5;
};

int main()
{
    std::shared_ptr<Win> sharedptr;///holds null pointer
    sharedptr->disp();//// why its working
}

你不会得到 5。你可能会得到任何东西。就像评论中的人所说,这是未定义的行为。

关于c++ - 共享指针无需分配即可工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34764281/

相关文章:

c++ - std::shared_ptr 和初始化列表

c++ - 一个人如何降低 std::shared_ptr?

c++ - 我可以在没有自定义析构函数的情况下使用 std::shared_ptr 和 weak_ptr 创建共享对象池吗?

c++ - C++中如何正确定义常量

c++ - 如何在 OpenGL 或 Win32 中获取显卡型号名称?

c++ - C++中二维 vector 的列大小和行大小

c++ - 防止编码器在物理模拟中出现错误 "forget to divide by time"

c++ - 我可以在前向声明中默认模板参数吗

c++ - 检查是否存在(重载的)成员函数

c++ - 为什么要有 move 语义?