且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列出与引用一起使用,用作成员时更改行为

更新时间:2022-02-08 18:28:10

聚合初始化允许将引用绑定到临时对象(,这会导致生命周期延长)。您的第一个示例是聚合初始化,因为 node 是一个聚合。

Aggregate initialization allows binding references to temporaries (and this causes lifetime extension). Your first example is aggregate initialization because node is an aggregate.

但是,在构造函数成员初始化器列表中,它的格式不正确,无法将引用绑定到临时(C ++ 17 class.base.init / 11)。这是因为在这种情况下不会延长生命周期,并且允许它不可避免地会产生悬挂的参考。在第二个示例中, node 不是聚合,因为它具有用户提供的构造函数。

However, in a constructor member initializer list, it is ill-formed to bind a reference to a temporary (C++17 class.base.init/11). This is because there is no lifetime extension in that situation , and allowing it would inevitably produce a dangling reference. In the second example node is not an aggregate because it has a user-provided constructor.