C++ STL 列表的Push_back按值传递参数?
C++ STL list's Push_back takes argument pass by value?
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/相关文章:
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- C++类 - 初始化列表 - 递归 - 按值传递
- 将函数参数完美转发到函数指针:按值传递呢?
- 棘手的按值传递和按引用递归问题传递
- 不同于按值传递和常量引用传递的程序集
- 按值传递变量与按引用传递变量具有相同的结果
- 为什么按值传递QStringView比引用常量更快?
- 获取 std::函数以推断按引用传递/按值传递
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- 防止在按值传递对象(继承)时进行切片
- 按值传递类和结构
- C++按引用传递还是按值传递?
- 为什么在按值返回时创建临时对象,而不是在按值传递给函数参数时创建临时对象
- 可移动但不可复制的对象:按值传递还是按引用传递?
- const-ref传递的模板化参数是否经过优化,以便在足够小时按值传递
- 在C++中指针是按值传递的吗
- shared_ptr构造函数参数是否应按值传递
- 使用 std::move 将参数传递给函数,如果该参数声明为按值传递或使用移动操作数 &&,是否有区别?