错误使用nullptr的编译器错误

时间:2019-04-15 03:47:00

标签: c++ compiler-errors g++ ubuntu-18.04 nullptr

我正在尝试此SO Q / A Compiler error while using shared_ptr with a pointer to a pointer中提供的解决方案,但无法正确使用提供的解决方案。在带有g ++版本7.3的Ubuntu 18.04上仍然出现编译错误

这是我重现该问题的最低限度的完整示例

test.h

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


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


struct _test_
{
  shared_ptr<shared_ptr<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);
 struct _test_ test1;
 int main(void)
 {

   test1.flane_pointers(nullptr);
   shared_ptr<DataNode> node = newNode(1000);
 }

 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:11:31: error: no match for call to   ‘(std::shared_ptr<std::shared_ptr<ProxyNode> >) (std::nullptr_t)’
    test1.flane_pointers(nullptr);
                                ^

您还尝试了什么?

我也尝试在头文件中初始化 nullptr

  struct _test_
  {
   shared_ptr<shared_ptr<ProxyNode>> flane_pointers(nullptr);
  };

但是那也不起作用。我要去哪里错了?

我的目标

我要做的只是以下操作-我正在尝试初始化flane_pointers,这是指向nullptr的指针的向量。该声明是在头文件中进行的,它是什么类型的声明,我正在尝试在.cpp文件中对其进行初始化。这样做时,我得到了上面的编译错误。

   flane_pointers(nullptr)

更新

任何答案都可以解释此Compiler error while using shared_ptr with a pointer to a pointer中提供的初始化是否正确吗?

  std::shared_ptr<std::shared_ptr<ProxyNode> > ptr2ptr2ProxyNode(nullptr);

对我来说(而且我是C ++的新手),初始化看起来也像是一个函数调用。那不对吗?

3 个答案:

答案 0 :(得分:2)

在此行:

test1.flane_pointers(nullptr);

您正试图调用flane_pointers,就好像它是成员函数一样。 shared_ptr不能像函数一样调用,因此会出现编译器错误。

如果您想初始化flane_pointers,只需为其分配:

test1.flane_pointers = nullptr; 

或者,也可以在创建test1时进行分配:

// Initialize test1 with a nullptr
_test_ test1{nullptr}; 

答案 1 :(得分:1)

如果您打算将nullptr初始化为shared_ptr<shared_ptr<ProxyNode>> flane_pointers = nullptr; ,则应使用以下形式的初始化:

struct _test_

test1.flane_pointers = nullptr;

main

main中。

您尝试执行的另一种初始化形式被解释为struct _test_中的函数调用和 std::shared_ptr<std::shared_ptr<ProxyNode> > ptr2ptr2ProxyNode(nullptr); 中的函数声明。

在链接的帖子中,

main

位于{}中,并且只能解释为变量声明而不是函数调用,因为它没有函数调用语法,因为变量的开头是std :: shared_ptr>类型。

为避免混淆,最好(从C ++ 11开始)使用大括号括起来的初始化器{{1}}声明和初始化变量。

答案 2 :(得分:1)

test1.flane_pointers(nullptr);

被视为函数调用。这就是错误的根源。请改用分配。

test1.flane_pointers = nullptr;

shared_ptr<shared_ptr<ProxyNode>> flane_pointers(nullptr);

不是成员内初始化的有效形式。您可以使用

shared_ptr<shared_ptr<ProxyNode>> flane_pointers{nullptr};

shared_ptr<shared_ptr<ProxyNode>> flane_pointers = nullptr;
相关问题