【发布时间】:2019-09-03 06:02:47
【问题描述】:
我是在 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;
};
以及实际代码test.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++ 风格,调用指向指针的指针,然后如何修复编译器错误。如果看起来我遗漏了一些明显的东西,我深表歉意。
【问题讨论】:
标签: c++ compiler-errors g++ shared-ptr smart-pointers