返回列表前端 (C++) 的类型
Return type of list front (C++)
所以我想为程序的一部分使用列表。我正在尝试熟悉库列表,所以我写了一个快速的小程序来帮助自己了解发生了什么。这一切都工作正常,但有一件事我不明白。
据此: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
};
如您所见,它接受对另一个room
的const
引用,并通过从传入的 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++标准中的相应部分。
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型