如何访问std :: shared_ptr的内容?

时间:2015-06-08 15:06:23

标签: c++ pointers c++11 netbeans shared-ptr

这是我的代码。

std::shared_ptr<WSUStudent> WSUStudent::registerStudent(
   std::string lastName,
   std::string firstName
)
{
   auto result = std::shared_ptr<WSUStudent>(new WSUStudent(lastName, firstName));

   s_allStudents.insert(&result);

   return result;
}

我已成功设法更改函数,因此返回shared_ptr而不是普通指针。我成功地封装了新的&#39;具有共享指针的语句,根据赋值(我认为),但下面的代码行是&#39; auto&#39;没有&amp ;,没有工作,并且它不能和&amp ;.一起工作。我收到一个错误,指出没有匹配的函数调用,有或没有&amp ;.那行代码试图将新学生(或指向新学生的指针?)插入所有学生的列表中。然而,&#39;插入&#39;方法没有在本地覆盖,所以我不太清楚这里要做什么。错误打印在下面。

/mnt/hgfs/Data Structures and Algorithms/HW04/WSUStudent.cpp:146:32: error: no matching function for call to ‘std::set<WSUStudent*>::insert(std::shared_ptr<WSUStudent>*)’
    s_allStudents.insert(&result);

这项任务的目的是通过将普通指针转换为弱指针和共享指针来修复内存泄漏(通过指针删除不会被删除的新语句)。原始代码如下。

WSUStudent *WSUStudent::registerStudent(
   std::string lastName,
   std::string firstName
)
{
   auto result = new WSUStudent(lastName, firstName);

   s_allStudents.insert(result);

   return result;
}

我是不是错了?我无法运行s_allStudents行。

2 个答案:

答案 0 :(得分:3)

鉴于s_allStudents的类型,您可以使用:

s_allStudents.insert(result.get());

但是,更好的选择是更改s_allStudents的类型。

static std::set<std::shared_ptr<WSUStudent>> s_allStudents;

并使用:

s_allStudents.insert(result);

<强>更新

operator<()的默认shared_ptrs_allStudents中的对象将按指针值排序。如果您想使用不同的标准对对象进行排序,则需要将自定义函子/函数定义为模板的参数。

struct MyCompare
{
   bool operator<(shared_ptr<WSUStudent> const& lhs,
                  shared_ptr<WSUStudent> const& rhs) const
   {
      // Implement the logic ...
   }
};

并将其用作:

static std::set<std::shared_ptr<WSUStudent>, MyCompare> s_allStudents;

答案 1 :(得分:1)

如果您要返回std::shared_ptr<WSUStudent>,那么您将返回所有权对您创建的对象的权限 - 这意味着其他人会在某个时候尝试删除它。

除非您 保持所有权,否则您的指针可能会在您完成之前已删除。因此,您还需要将std::shared_ptr存储在静态集中:

我猜你是如何使用这个课程但我的意思是这样的:

class WSUStudent
{
    // you really need to store shared pointers in here
    static std::set<std::shared_ptr<WSUStudent>> s_allStudents;

    std::string lastName;
    std::string firstName;

    // only the static factory function can make students
    WSUStudent(
        const std::string& lastName, // passing by const& is more usual (idiomatic)
        const std::string& firstName)
    : lastName(lastName)
    , firstName(firstName)
    {
    }

public:

    static std::shared_ptr<WSUStudent> registerStudent(
        const std::string& lastName,
        const std::string& firstName);
};

std::shared_ptr<WSUStudent> WSUStudent::registerStudent(
    const std::string& lastName,
    const std::string& firstName
)
{
    auto result = std::shared_ptr<WSUStudent>(new WSUStudent(lastName, firstName));

    // put the shared student in your set
    s_allStudents.insert(result);

    return result;
}

// define your set
std::set<std::shared_ptr<WSUStudent>> WSUStudent::s_allStudents;

int main ()
{
    // make students
    auto s = WSUStudent::registerStudent("bill", "bob");
    // all deletions should be in order
}
相关问题