不可复制类型的整数可索引 RAII 容器

Integer index-able RAII container for non-copyable type(不可复制类型的整数可索引 RAII 容器)

本文介绍了不可复制类型的整数可索引 RAII 容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有标准容器具有与 vector<T> 相同的通用 API,但通过直接默认构造填充新位置?

Is there a standard container that has the same general API as vector<T> but that populates new locations via direct default construction?

背景:

我有一个不允许复制但有一个默认构造函数的类型,我真正想做的是:

I have a type that disallows copying but has a default constructor and what I really want to do is this:

vector<NoCopy> bag(some_size);

// use bag[i]'s

return; // bag & contents get correctly cleaned up. 

但是,这不起作用,因为 vector<T>(int) 是根据默认构造一个对象然后将其复制到每个新位置来实现的.

However, this doesn't work because vector<T>(int) is implemented in terms of default constructing an object and then copying it into each of the new locations.

不是 C++0xB(又名 C++11)

Not C++0xB (a.k.a. C++11)

推荐答案

一种选择是升级到符合 C++11 的标准库实现.

One option would be to upgrade to a C++11-compliant Standard Library implementation.

在 C++11 中,vector(size_type) 构造函数默认将 N 个元素构造到容器中.它既不复制也不移动任何元素.

In C++11, the vector(size_type) constructor default constructs N elements into the container. It neither copies nor moves any elements.

Visual C++ 2010 不支持这个 C++11 特性;我相信 Visual C++ 11 Developer Preview 确实正确支持它.我不知道最新版本的 libstdc++ 是否支持这个;我会怀疑 libc++ 会.

Visual C++ 2010 does not support this C++11 feature; I believe the Visual C++ 11 Developer Preview does correctly support it though. I do not know whether recent versions of libstdc++ support this; I would suspect that libc++ does.

这篇关于不可复制类型的整数可索引 RAII 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:不可复制类型的整数可索引 RAII 容器

基础教程推荐