gpt4 book ai didi

c++ - 是否有在标准容器中使用 unique_ptr 的透明方法?

转载 作者:太空狗 更新时间:2023-10-29 23:27:31 27 4
gpt4 key购买 nike

是否有在容器中使用 std::unique_ptr 的透明方法?

#include <iostream>                                                                                                                         
#include <memory>
#include <map>

struct method {
virtual ~method() { std::cout << "f\n"; };
};
typedef std::unique_ptr<method> MPTR;

std::map<int, MPTR> tbl;

void insert(int id, method *m) {
tbl.insert({id,std::unique_ptr<method>(m)});
};

void set(int id, method *m) {
tbl[id] = std::unique_ptr<method>(m);
};

int main(int argc, char **argv) {

insert(1,new method());
set(1,new method());
return 0;
}

我想使用 tbl.insert({id,m});tbl[id] = m; 等,而不必包装/为每次访问解包。

  • 是否有用于 unique_ptr 的标准容器的实现?特别是 std::map
  • 如何实现透明接口(interface)?

最佳答案

通常,我们不想隐式创建std::unique_ptr 因为that can be dangerous .

在此示例中,我建议从unique_ptr 而不是裸new 开始。这makes sure the entire lifetime is tracked .

#include <memory>
int main(int argc, char **argv) {
auto m = std::make_unique<method>();
insert(1, std::move(m));
}

insert 中,您还可以使用 std::move 将所有权转移到集合。

关于c++ - 是否有在标准容器中使用 unique_ptr 的透明方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54223750/

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