STL容器和不可复制(和不可移动)对象 [英] STL containers and non copyable (and non movable) objects

查看:291
本文介绍了STL容器和不可复制(和不可移动)对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于STL容器要求所有内容都是可复制和可分配的,在使用非可复制对象时,最好的习惯是什么?

Since STL containers require that all contents be copyable and assignable, what is the prefered idiom when working with non copyable objects?

我可以想出两种不同的方法:

I can think of two different approaches:


  1. 智能)指针而不是STL容器中的对象。

  1. Store (smart) pointers rather than the objects in STL containers.

删除STL容器并实现我自己的列表(例如每个对象必须包含一个指向下一个目的)。

Get rid of STL containers and implement my own lists (e.g. each object must include a pointer to the next object).

第二种方法的主要缺点是析构函数的实现(如果next对象在当前对象之前被销毁)

Main drawback of the second approach is implementation of destructors (should the "next" object be destroyed before the current one in a recursive way?)

推荐答案

我会选择方法#1:ie store smart pointers

I'd choose approach #1: i.e. store smart pointers to objects in STL containers.

请注意,在STL容器中存储非拥有的原始指针(例如观察原始指针)是很好的,但是存储拥有原始指针是一个泄漏:使用 shared_ptr + 11的 unique_ptr

Note that it's fine to store non-owning raw pointers in STL containers (e.g. observing raw pointers), but storing owning raw pointers is a "leaktrocity": use shared_ptr or new C++11's unique_ptr instead.

划痕需要大量的时间和精力,我相信你不能在合理的时间框架内匹配丰富的商业质量的STL库。

As for #2, writing your own containers from scratch requires lots of time and energy, and I believe you can't match the richness of a full commercial-quality STL library implementation in a reasonable time-frame.

这篇关于STL容器和不可复制(和不可移动)对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆