c++ - operator new[] 只分配一个元素,不管请求了多少(C++)

标签 c++ arrays new-operator

<分区>

对于介绍性的 C++ 类(class)作业(当然是今晚!),我必须实现自己的 Vector 类。大多数一切似乎都在工作,除了我在 VS2012 的调试器中注意到它似乎实际上只分配了 _arr[] 中的一个元素。无论请求的元素数量 (n) 是多少,它只分配数组中的一个元素。我按照调试跟踪,new[] 收到 20 个请求(请求的 5 个元素 * 4 个字节用于 int),但是当我稍后检查 sizeof(_arr) 时,它只显示 4 个字节。其他 16 个字节在哪里结束?为什么缺少其他 4 个元素?没有指示错误,也没有抛出异常。

template <typename T>
void Vector<T>::Add ( const T& val )
{
    // Check if a new element would grow beyond the current allocation.
    if ( _length + 1 > _allocSize )
    {
        size_t n = 5; // <-- Set statically for this example
        // Create a new array of the requested size
        try
        {
            T* newArr = new (std::nothrow) T[n]();
            if( newArr == NULL )
                throw VectorException( VECTOR_CANNOT_GROW,
                     "Vector::Add", _length, n );
            // Copy the old array into the new array
            if( _length > 0 )
                for( size_t idx = 0; idx < _length; idx++ )
                    newArr[idx] = _arr[idx];
            // Delete any dynamic memory allocated to the old array.
            delete[] _arr;

            // Note: _sizeof(newArr) here indicates only 4 bytes!!!

            // Point _arr to the new array
            _arr = newArr;

            // Update the allocated size to the new array size
            _allocSize = n;
        }
        catch ( VectorException &cException )
        {
            cerr << cException.GetError() << endl;
            DoExit( cException.GetErrorNum() );
        }
    }
    // Add the new item to the end of the array and update the length.
    _arr[ _length++ ] = val;
}

此外,我已经能够按预期使用 Vectors,但恐怕我实际上只是在访问数组本身之外的内存。好像是分配给程序的,但是在数组中没有出现。

还是我只是糊涂了,真的一点问题都没有?

感谢您的帮助!

最佳答案

when I check sizeof(_arr) later, it only shows 4 bytes

sizeof 是一个编译时特性。 new[] 根据运行时参数分配内存。最终结果是 sizeof 没有您要求的信息。相反,它告诉您指向数组的指针是 4 个字节,这对于 32 位代码是正常的。

new[] 正在正确分配内存。不幸的是,您正在寻找的信息在标准 C++ 中不可用,并且您的调试器提供了一种误导性的观点。

关于c++ - operator new[] 只分配一个元素,不管请求了多少(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577089/

相关文章:

C++ 'CA2W' : identifier not found

c++ - 用于稀疏数据查找的高效数据结构

c++ - 我可以创建一个可以复制任意大小的二维数组的 'CopyArray' 函数吗?

javascript项目拼接自己超出列表

c++ - 基于函数参数 C++ 创建对象

c++ - 如何在 C++ 中读取 UTF-8 文件数据?

c - 遇到文件 I/O 和字符串数组的问题

javascript - 在 array.indexOf(x) 中搜索总是返回 -1 即使该值存在

c++ - 推回 vector 指针时如何解决读取访问冲突

c++ - 是否可以完全禁用默认的 C++ new 运算符?