有关智能指针的代码失败

codes about smart pointer failed

本文关键字:代码 失败 指针 智能      更新时间:2023-10-16

我刚刚在c++ Primer中尝试了智能指针的代码,我没有发现任何问题。这和书中的密码非常相似。

代码:

#include <vector> 
#include <memory> 
std::shared_ptr<std::vector<int>> *my_malloc() { 
    return std::make_shared<std::vector<int>>(); 
} 

编译器错误:

12_7.cc:6:12: error: no viable conversion from
  'typename enable_if<!is_array<vector<int, allocator<int> > >::value, shared_ptr<vector<int, allocator<int> > > >::type'
  (aka 'std::__1::shared_ptr<std::__1::vector<int, std::__1::allocator<int> > >')
 to 
  'std::shared_ptr<std::vector<int> > *' 
return std::make_shared<std::vector<int>>(); 
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
1 error generated. 

您的my_malloc函数声明它返回指向共享指针的指针(这很奇怪,可能是错误的),然后您返回共享指针(就像您应该的那样)。试着

std::shared_ptr<std::vector<int>> my_malloc() { 
  return std::make_shared<std::vector<int>>(); 
}

std::shared_ptr<std::vector<int>> *表示指向的指针,指向整型向量的共享指针。您正在尝试从应该返回shared_ptr*的函数返回shared_ptr

您可能希望您的函数返回一个实际的shared_ptr,而不是一个(非共享的)指针,因此只需删除*