代码之家  ›  专栏  ›  技术社区  ›  Casebash

为什么我们可以删除数组,但不知道C/C++中的长度?

  •  18
  • Casebash  · 技术社区  · 15 年前

    我们如何能够删除动态分配的数组,但我们无法找出它们有多少个元素?我们不能把内存位置的大小除以每个对象的大小吗?

    7 回复  |  直到 7 年前
        1
  •  16
  •   Tony Delroy    15 年前

        2
  •  6
  •   Fred Foo    15 年前

    malloc new

    int *a = new int[N];
    std::cout << sizeof(a);
    

    sizeof(int *)

        3
  •  5
  •   MOnsDaR    15 年前
        4
  •  4
  •   Martin Ba    15 年前

    malloc

        5
  •  3
  •   Will    15 年前

    AllocSize()

        6
  •  3
  •   justin    15 年前

    new[]

    size_t

    std::vector

    /* holds an array of @a TValue objects which are created at construction and destroyed at destruction. interface borrows bits from std::vector */
    template<typename TValue>
    class t_array {
        t_array(const t_array&); // prohibited
        t_array operator=(const t_array&); // prohibited
        typedef t_array<TValue>This;
    public:
        typedef TValue value_type;
        typedef value_type* pointer;
        typedef const value_type* const_pointer;
        typedef value_type* const pointer_const;
        typedef const value_type* const const_pointer_const;
        typedef value_type& reference;
        typedef const value_type& const_reference;
    
        /** creates @a count objects, using the default ctor */
        t_array(const size_t& count) : d_objects(new value_type[count]), d_count(count) {
            assert(this->d_objects);
            assert(this->d_count);
        }
    
        /** this owns @a objects */
        t_array(pointer_const objects, const size_t& count) : d_objects(objects), d_count(count) {
            assert(this->d_objects);
            assert(this->d_count);
        }
    
        ~ t_array() {
            delete[] this->d_objects;
        }
    
        const size_t& size() const {
            return this->d_count;
        }
    
        bool empty() const {
            return 0 == this->size();
        }
    
        /* element access */
        reference at(const size_t& idx) {
            assert(idx < this->size());
            return this->d_objects[idx];
        }
    
        const_reference at(const size_t& idx) const {
            assert(idx < this->size());
            return this->d_objects[idx];
        }
    
        reference operator[](const size_t& idx) {
            assert(idx < this->size());
            return this->d_objects[idx];
        }
    
        const_reference operator[](const size_t& idx) const {
            assert(idx < this->size());
            return this->d_objects[idx];
        }
    
        pointer data() {
            return this->d_objects;
        }
    
        const_pointer data() const {
            return this->d_objects;
        }
    
    private:
        pointer_const d_objects;
        const size_t d_count;
    };
    

    • t_array

        7
  •  1
  •   Lorenzo Stella    15 年前