将shared_ptr与指向指针的指针一起使用时出现编译器错误

Compiler error while using shared_ptr with a pointer to a pointer

本文关键字:指针 错误 编译器 一起 shared ptr      更新时间:2023-10-16

我是C++中使用智能指针的新手,我目前的问题是我正在将 C 代码转换为 C++ (C++11/14/17(,并且我在理解使用带有指向指针的指针的 shared_ptr 时遇到了一些问题。我推导出了一个玩具示例,我认为它说明了问题

以下是头文件

#include <memory>
using std::shared_ptr;
struct DataNode
{
  shared_ptr<DataNode> next;
} ;

 struct ProxyNode
 {
   shared_ptr<DataNode> pointers[5];
 } ;

 struct _test_
 {
   ProxyNode** flane_pointers;
  };

以及实际的代码测试.cpp

#include <stdint.h>
#include "test.h"

shared_ptr<DataNode> newNode(uint64_t key);
shared_ptr<ProxyNode> newProxyNode(shared_ptr<DataNode> node);
int main(void)
{
  // Need help converting this to a C++ style calling
  ProxyNode** flane_pointers = (ProxyNode**)malloc(sizeof(ProxyNode*) * 100000);
  // Here is my attempt (incomplete)
  ProxyNode** flane_pointers = new shared_ptr<ProxyNode> ?
  shared_ptr<DataNode> node = newNode(1000);
  flane_pointers[1] = newProxyNode(node)
} 
shared_ptr<ProxyNode> newProxyNode(shared_ptr<DataNode> node) 
{
  shared_ptr<ProxyNode> proxy(new ProxyNode());
 return proxy;
}
shared_ptr<DataNode> newNode(uint64_t key) 
{
 shared_ptr<DataNode> node(new DataNode());
 return node;
}

我收到这些编译器错误 -

 test.cpp: In function ‘int main()’:
 test.cpp:12:42: error: cannot convert ‘std::shared_ptr<ProxyNode>’ to  ‘ProxyNode*’ in assignment
  flane_pointers[1] = newProxyNode(node)

编译方式

  g++ -c -g test.h test.cpp

g++ 版本是 7.3.0(在 Ubuntu 18 上(

我需要帮助转换 C 样式 malloc 分配,使用 C++ 样式调用指向指针的指针,然后如何修复编译器错误。如果看起来我错过了一些明显的东西,我深表歉意。

如果这个ProxyNode** flane_pointers;应该是ProxyNode矩阵,那么最简单的方法是创建包含ProxyNode的向量向量,如下所示:

struct DataNode
{
    std::shared_ptr<DataNode> next;
};

struct ProxyNode
{
    // here instead of C style array you can use std::array
    std::shared_ptr<DataNode> pointers[5];
};
TEST(xxx, yyy) {
    std::vector<std::vector<ProxyNode> > matrixOfProxyNodes;
    // insert empty vector of ProxyNode
    matrixOfProxyNodes.push_back(std::vector<ProxyNode>());
    // insert ProxyNode to the first vector of ProxyNodes
    matrixOfProxyNodes[0].push_back(ProxyNode());
    // insert shared_ptr to DataNode in position 0, 0 of matrix of ProxyNodes
    matrixOfProxyNodes[0][0].pointers[0] = std::make_shared<DataNode>();
}

如果你真的需要指针到指针(但我真的看不出这样做的目的(,你可以这样做:

    // create shared pointer to shared pointer to ProxyNode
    // and initialize it to nullptr
    std::shared_ptr<std::shared_ptr<ProxyNode> > ptr2ptr2ProxyNode(nullptr);
    // dynamically create new shared_ptr to ProxyNode
    ptr2ptr2ProxyNode.reset(new std::shared_ptr<ProxyNode>(nullptr));
    // dynamically create ProxyNode
    ptr2ptr2ProxyNode->reset(new ProxyNode());
    (*ptr2ptr2ProxyNode)->pointers[0] = std::make_shared<DataNode>();

请注意,std::shared_ptr的行为与原始指针不完全相同,例如,您不应该为 shared_ptr 分配内存 operator new[] 。下面解释了原因。

另外,我看到您可能想要实现某种列表或其他链。 std::shared_ptr可能会遭受循环依赖,因此请小心并在需要时使用std::weak_ptr