C++ STL 列表的Push_back按值传递参数?

C++ STL list's Push_back takes argument pass by value?

本文关键字:back 按值传递 参数 Push STL 列表 C++      更新时间:2023-10-16

c++ STL::list的push_back函数接受参数作为值传递。但是,当参数超出作用域时,仍然可以访问列表的元素。

 typedef std::list<MyObject> mylist;
 void function1()
 {
     MyObject obj;<<<< local scope
    ...
     mylist.push_back(obj);
 }
void function2()
{
//On Iterating the list "mylist" able to access objs in the list properly even though the scope of obj is lost in function1.
}
void push_back (const value_type& val);
void push_back (value_type&& val);

第一个签名接受const引用,但会复制它。第二个函数接受一个右值引用,并将其移动。

来源:http://www.cplusplus.com/reference/list/list/push_back/

函数签名

void push_back (const value_type& val);

和传递的值被复制到列表中。因此,您可以将其视为"按值传递"(以可操作的方式)。在c++ 11中还有

void push_back (value_type&& val);

表示将值移动到列表中的可能性

应该按引用传递:

http://www.cplusplus.com/reference/list/list/push_back/