我一直在学习智能指针,最近在类里面我的助教说我们永远不要使用原始指针。现在,我已经做了很多在线阅读,并在这个网站上看了不同的问题,但是我仍然对智能指针的某些方面感到困惑。我的问题是:如果要在程序中使用它,我将使用哪个智能指针?我将显示一些代码。

因此,我有一个基本的Application类,用于从AI类声明对象。注意:出于测试原因,我有两个不同的智能指针,一个是唯一的,一个是共享的。

// Application class in Application.h

class Application
{
public:
    Application(){}
    ~Application(){}

    //... additional non-important variables and such

    unique_ptr<AI> *u_AI; // AI object using a unique pointer
    shared_ptr<AI> *s_AI; // AI object using a shared pointer

    //... additional non-important variables and such

    void init();
    void update();
};

// AI class in AI.h

class AI
{
public:
    AI(){}
    ~AI(){}

    bool isGoingFirst;
};

在应用程序初始化函数中,我想创建AI对象,然后在更新函数中使用它。我不确定我是否完全正确地声明了指针,但是我知道它可以编译并且可以在init函数中分配和打印数据。下面有更多代码。
void Application::init()
{
    //.. other initialization's.

    std::shared_ptr<AI> temp(new AI());
    sh_AI = &temp;
    sh_AI->isGoingFirst = true;

    //.. other initialization's.
    // Function ends.
}

void Application::update()
{
    if(sh_AI->get()->isGoingFirst == true)
    {
         // Do something
    }
    else
    {
        // Do something else
    }

    // Other code below
}

在程序的稍后部分,将调用update函数,该函数使用与我在类Application中声明的AI智能指针相同的函数。我发现是智能指针AI对象正在被删除。我知道智能指针具有自动内存管理功能,但是有没有一种智能指针可以让您在不同的功能中使用它,而不会造成任何重大问题,例如内存泄漏或悬挂引用?还是我错过了智能指针的全部要点?

很抱歉,如果在另一个问题中回答了这个问题,但我阅读了许多其他问题,虽然我对智能指针有了更多的了解,但我仍在学习。谢谢!

最佳答案

正如Neil Kirk在评论中指出的那样,这些声明不是您想要的:

unique_ptr<AI> *u_AI; // AI object using a unique pointer
shared_ptr<AI> *s_AI; // AI object using a shared pointer

u_AI和s_AI仍然是原始指针的对象。重点是消除直接管理原始指针的需要。所以现在您将它们替换为:
unique_ptr<AI> u_AI; // AI object using a unique pointer
shared_ptr<AI> s_AI; // AI object using a shared pointer

要分配创建的指针,请使用函数make_unique或make_shared:
u_AI = unique_ptr<AI>(new AI()); // Yu may be able to use make_unique like
                                 // make_shared but it's new to C++14. may not be available
s_AI = make_shared<AI>();

然后,当您需要访问它们时,只需假装它们是指针,因此在更新功能中:
if(sh_AI->get()->isGoingFirst == true)

变成:
if(sh_AI->isGoingFirst == true)

至于何时使用unique_ptr与shared_ptr,您可以通过回答以下问题来回答:当有人复制Application时,我想怎么办?即:
Application app1;
app1.init();
Application app2 = app1; // ?? what happens to AI object in app2?

有3种可能的答案:
  • 我希望app2中有AI的额外副本。 在这种情况下,您使用unique_ptr并确保实现用于复制的复制构造函数。
  • 我希望app2和app1共享AI的副本。 在这种情况下,您使用shared_ptr,默认的复制构造函数将为您完成这项工作。
  • 我不希望有Application的副本。 (对于名为Application的类有意义)。在这种情况下,这并不重要(在这种情况下,我将默认为unique_ptr)并删除复制构造函数:

    Application(const Application&)=删除;
  • 关于c++ - 使用智能指针作为类成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26473733/

    10-11 22:39
    查看更多