错误使用 nullptr 的编译器错误

Compiler errors with incorrect use of nullptr

我正在尝试此 SO Q/A 中提供的解决方案,但我无法以正确的方式使用提供的解决方案。我在 Ubuntu 18.04 和 g++ 版本 7.3

上仍然遇到编译错误

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

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)

更新

任何答案都可以解释此 中提供的初始化是否正确吗?

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

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

如果您打算将 flane_pointers 初始化为 nullptr,您应该使用以下形式的初始化:

shared_ptr<shared_ptr<ProxyNode>> flane_pointers = nullptr;

struct _test_

test1.flane_pointers = nullptr; 

main.

您尝试执行的另一种初始化形式在 main 中被解释为函数调用,在 struct _test_ 中被解释为函数声明。

在链接中post,

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

main中,只能解释为变量声明而不是函数调用,因为它没有函数调用语法,因为变量前面有类型std::shared_ptr>。

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

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;

这一行:

test1.flane_pointers(nullptr);

您正在尝试调用 flane_pointers,就好像它是一个成员函数一样。 shared_ptr 不能像函数一样调用,所以你得到编译器错误。

如果要初始化flane_pointers,直接赋值给它即可:

test1.flane_pointers = nullptr; 

或者,您可以在创建 test1:

时进行分配
// Initialize test1 with a nullptr
_test_ test1{nullptr};