相关疑难解决方法(0)

在空std :: vector上使用operator []

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

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

    //do work

} // exception safe deallocation
Run Code Online (Sandbox Code Playgroud)

我已多次使用此约定没有问题,但是我最近将一些代码移植到Win32 VisualStudio2010(之前只在MacOS/Linux上)并且我的单元测试正在破坏(stdlib抛出一个断言)当矢量大小恰好是零.

我知道写一个这样的数组会有问题,但是这个假设打破了这个解决方案作为原始指针的替代.考虑以下函数,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;
}
Run Code Online (Sandbox Code Playgroud)

虽然可以说是多余的,但上面的代码完全合法(我相信),而下面的代码将在VisualStudio2010上抛出一个断言

void foo (int n) {
   std::vector<char> scoped_array (n);
   char* pointer = …
Run Code Online (Sandbox Code Playgroud)

c++ vector visual-studio-2010

8
推荐指数
2
解决办法
2620
查看次数

标签 统计

c++ ×1

vector ×1

visual-studio-2010 ×1