首页 > 解决方案 > 错误使用 nullptr 导致编译器错误

问题描述

我正在尝试此 SO Q/A编译器错误中提供的解决方案,同时将 shared_ptr 与指向指针的指针一起使用,但我无法以正确的方式使用提供的解决方案。我仍然在使用 g++ 7.3 版的 Ubuntu 18.04 上遇到编译错误

这是我重现问题的最小完整可验证示例

测试.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;
};

测试.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)

更新

任何答案都可以解释在使用带有指向指针的指针的 shared_ptr 时此编译器错误中提供的初始化是否 正确?

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

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

标签: c++compiler-errorsg++ubuntu-18.04nullptr

解决方案


在这条线上:

test1.flane_pointers(nullptr);

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

如果你想初始化flane_pointers,你可以分配给它:

test1.flane_pointers = nullptr; 

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

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

推荐阅读