gpt4 book ai didi

c++ - 如何在两个 boost::intrusive::slist 对象之间传输节点

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:38:29 28 4
gpt4 key购买 nike

在两个boost::intrusive::slist<boost::intrusive::cache_last<true>>之间转移节点是否有效对象?类似下面的内容

auto one = boost::intrusive::slist<Node, boost::intrusive::cache_last<true>>{};
auto two = boost::intrusive::slist<Node, boost::intrusive::cache_last<true>>{};

auto node = std::make_unique<Node>();
one.push_back(*node);

auto& front = one.front();
one.pop_front();
two.push_back(front);

我遇到了段错误,以及 boost 版本 1.70.0 的断言失败 https://wandbox.org/permlink/nWHakTYUiVBGKH6I .我该如何解决这个问题?


注意:我无法分配新节点并复制旧节点,因为我正在使用侵入式列表来控制分配发生的时间和地点。

最佳答案

这似乎是splice的目的方法:

Effects: Transfers all the elements of list x to this list, before the the element pointed by it. No destructors or copy constructors are called.

two.splice(two.end(), one, one.begin());

完整的工作演示:

#include <iostream>
#include <string>
#include <boost/intrusive/slist.hpp>

struct Node : public boost::intrusive::slist_base_hook<>
{
int i;
std::string s;

Node(int i, std::string s) : i(i), s(std::move(s)) {}
};

using NodeList = boost::intrusive::slist<Node, boost::intrusive::cache_last<true>>;

int main()
{
NodeList one;
NodeList two;

auto show = [&](auto text){
std::cout <<text <<"\n one\n";
for (auto & item : one) { std::cout <<" " <<item.i <<' ' <<item.s <<'\n'; }
std::cout <<" two\n";
for (auto & item : two) { std::cout <<" " <<item.i <<' ' <<item.s <<'\n'; }
};


one.push_back(*new Node(42, "hello"));
show("before splice");

two.splice(two.end(), one, one.begin());
show("after splice");

one.clear_and_dispose([](Node * ptr){ delete ptr; });
two.clear_and_dispose([](Node * ptr){ delete ptr; });
return 0;
}

运行时,会写:

before splice
one
42 hello
two
after splice
one
two
42 hello

关于c++ - 如何在两个 boost::intrusive::slist 对象之间传输节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800505/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com