当你使用push_back
将元素插入列表中,push_back
创建一个插入到列表中的副本。一个解决方案是使用std::reference_wrapper http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper相反,作为列表的基础类型,例如
std::list<std::reference_wrapper<Foo>> lst;
然后像这样推入它
lst.push_back(foo);
这是一个超级简单的示例,向您展示了它是如何工作的:
#include <functional>
#include <iostream>
#include <list>
int main()
{
int i = 42;
std::list<std::reference_wrapper<int>> lst;
lst.push_back(i); // we add a "reference" into the list
lst.front().get() = 10; // we update the list
std::cout << i; // the initial i was modified!
}
Live on Coliru http://coliru.stacked-crooked.com/a/b615243802938ad9
你需要reference_wrapper
因为您不能简单地创建引用列表,例如std::list<Foo&>
。或者,您可以使用指针,但我发现reference_wrapper
方法更加透明。
在上面的简单示例中请注意需要使用std::reference_wrapper::get() http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/get获取底层参考,如reference_wrapper
位于赋值运算符的左侧,因此不会隐式转换为int
via [std::reference_wrapper::operator T&
.
以下是修改后使用的完整工作代码reference_wrapper
s:
http://coliru.stacked-crooked.com/a/fb1fd67996d6e5e9 http://coliru.stacked-crooked.com/a/fb1fd67996d6e5e9