返回列表前端 (C++) 的类型

Return type of list front (C++)

本文关键字:类型 C++ 列表 前端 返回      更新时间:2023-10-16

所以我想为程序的一部分使用列表。我正在尝试熟悉库列表,所以我写了一个快速的小程序来帮助自己了解发生了什么。这一切都工作正常,但有一件事我不明白。

据此:http://www.cplusplus.com/reference/list/list/front/Front 函数的返回类型应该是第一个元素(在本例中为唯一元素)的类型(在本例中为 room)的引用

但是我能够在不必引用的情况下访问这些值,因为似乎所有值都是直接传递的(而不是通过引用传递的)。这是意料之中的吗?网站有误吗?我的编译器有误吗(CodeBlocks 13.12)?

这是我的代码:

#include <iostream>
#include <list>
using namespace std;
struct room {
    int content;
    struct room * north;
    struct room * south;
    struct room * east;
    struct room * west;
} ;
int main ()
{
    list<room> mylist;
    cout << ( mylist.empty() ? "List is empty.n" : "List is not empty.n" ) << endl;
    room * room1 = new room;
    room1->content = 15;
    cout
    << room1->content << "n"
    << room1->north << "n"
    << room1->south << "n"
    << room1->east << "n"
    << room1->west << "n";
    cout << "n" << room1 << endl;
    mylist.push_front(*room1);
    cout << ( mylist.empty() ? "nList is empty.n" : "nList is not empty.n" ) << endl;
    delete room1;
    room test_room = mylist.front();
    cout
    << test_room.content << "n"
    << test_room.north << "n"
    << test_room.south << "n"
    << test_room.east << "n"
    << test_room.west << "n";
    cout << "n" << &test_room << endl;
    return 0;
}
有两种

类型的构造函数会自动添加到您声明的任何类中:默认构造函数,默认初始化该类的所有成员§12.1.4复制构造函数§12.8.7

在您的情况下,我们必须看一下复制构造函数

复制构造函数的声明如下所示(如果您将其专门写下来§12.8.8):

struct room{
    room(const room&); // Copy-Ctor, implicitly added by the compiler
};

如您所见,它接受对另一个roomconst引用,并通过从传入的 room 复制来启动自身的所有值。


发生的第一件事是列表添加了您传递到mylist.push_front(*room1) room的副本(您可以看到push_front()通过 const-ref §23.3.5.4获取元素,但在内部复制它们。为此,第一次调用复制构造函数。

当您稍后使用 mylist.front() 访问该元素时,它会返回一个引用,但由于您初始化的值为 room ,而不是引用 - room test_room = mylist.front(); - 复制构造函数被第二次调用。要通过引用正确捕获列表的前面,您需要做 room& test_room = mylist.front(); .

注意:所有§nbr均参考C++标准中的相应部分。