在空std :: vector上使用operator [] [英] Using operator[] on empty std::vector

查看:139
本文介绍了在空std :: vector上使用operator []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前被告知,使用 std :: vector作为c ++中的异常安全动态数组是常见的地方,而不是分配原始数组...例如

I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for example

{
    std::vector<char> scoped_array (size);
    char* pointer = &scoped_array[0];

    //do work

} // exception safe deallocation


$ b我已经使用这个约定多次没有问题,但我最近移植一些代码到Win32 VisualStudio2010(以前它只在MacOS / Linux)和我的单元测试

I have used this convention multiple times with no problems, however I have recently ported some code to Win32 VisualStudio2010 (previously it was only on MacOS/Linux) and my unit tests are breaking (stdlib throws an assert) when the vector size happens to be zero.

我理解,写入一个这样的数组将是一个问题,当向量大小恰好为零时,stdlib会抛出一个断言。但是这个假设打破了这个解决方案作为替换原始指针。请考虑以下函数: n = 0

I understand that writing to an such an array would be a problem, but this assumption breaks this solution as a replacement to raw pointers. Consider the following functions with n = 0

void foo (int n) {
   char* raw_array = new char[n];
   char* pointer = raw_array;
   file.read ( pointer , n );
   for (int i = 0; i < n; ++i) {
      //do something
   }
   delete[] raw_array;
}

虽然可以说冗余,上面的代码是完全合法的下面的代码将在VisualStudio2010上抛出断言

While arguably redundant, the above code is perfectly legal (I believe), while the below code will throw an assertion on VisualStudio2010

void foo (int n) {
   std::vector<char> scoped_array (n);
   char* pointer = &scoped_array[0];
   file.read ( pointer , n );
   for (int i = 0; i < n; ++i) {
  //do something
   }
}

我一直使用未定义的行为吗?我在印象操作符[]下没有检查错误,这是一个有效的使用std :: vector<>。有没有人遇到这个问题?

Was I using undefined behavior all along? I was under the impression operator[] did no error checking, and this was a valid use of std::vector<>. Has anyone else encountered this problem?

- 编辑:
感谢所有有用的回应,是未定义的行为。
有一种方法可以替换上面的原始数组分配,使用 n = 0

--edit: Thanks for all the useful responses, in reply to people saying it is undefined behavior. Is there a way to replace the raw array allocation above which will work with n = 0?

n = 0 作为例外情况将解决问题(它会)。有许多模式,不需要特殊情况(如上面的原始指针示例),所以可能需要使用除std :: vector<>之外的其他东西?

While saying that checking for n=0 as an exceptional case will solve the problem (it will). There are many patters where no special case is needed (such as the raw pointer example above) so maybe using something other than std::vector<> would be needed?

推荐答案

请参阅 LWG问题464 < a>。这是一个已知的问题。
C ++ 0x(由MSVC 2010部分实现)通过添加一个 .data()成员来解决它。

这篇关于在空std :: vector上使用operator []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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