【问题标题】:Error initializing shared pointer with an array of list<int>使用 list<int> 数组初始化共享指针时出错
【发布时间】:2021-02-13 03:36:48
【问题描述】:

我正在尝试使用 shared_ptr 实现一个 Graph 类。我已将我的班级声明如下。

class Graph
{
    public:
        Graph(int V);
        Graph()=delete;
        void AddEdge(int src, int dest);
        void BFS(int s);
        ~Graph();
    private:
        int V;
        std::shared_ptr<std::list<int>[]> adj;
};

当我尝试在构造函数中初始化我的 adjList 时,出现编译错误。

Graph::Graph(int V)
{
    this->V = V;
    adj = std::make_shared<std::list<int>[]>(new std::list<int>[V]);
}

错误:

/usr/include/c++/9/bits/shared_ptr.h:717:39:   required from ‘std::shared_ptr<_Tp> std::make_shared(_Args&& ...) [with _Tp = std::__cxx11::list<int> []; _Args = {std::__cxx11::list<int, std::allocator<int> >*}]’
Graph.cpp:21:67:   required from here
/usr/include/c++/9/ext/new_allocator.h:145:20: error: no matching function for call to ‘std::__cxx11::list<int>::list(std::__cxx11::list<int>*)’

我做错了什么?

【问题讨论】:

  • 重新考虑您的方法。为什么你想要 std::shared_ptrstd::list 的数组?考虑使用std::lists 的std::vector 作为替代。
  • C++11 只有一个make_shared 函数。

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


【解决方案1】:

C++11 只有一个make_shared 函数。它的原型是这样的:

template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
  1. T 不能是数组。
  2. 该函数接受将传递给T 构造函数的参数,但std::list 没有可以接受new std::list&lt;int&gt;[V] 的构造函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多