【问题标题】:C++ vector resized with no reasonC++ 向量无故调整大小
【发布时间】:2014-02-21 14:54:04
【问题描述】:

我有这段代码:

#include<iostream>
#include<vector>

class A 
{
    private:
        static int x;

    public:
        A(){}
        ~A()
        {
            ++x;
            std::cout << "destroying A " << x << std::endl;
        }

};

int A::x(0);

int main (int args, char** argv) 
{
    std::vector<A> vectA(5); 
}

当我运行它时,我希望它打印 5 行(即为向量中的 5 个元素中的每一个调用析构函数),但实际上输出是:

destroying A 1
destroying A 2
destroying A 3
destroying A 4
destroying A 5
destroying A 6

嗯,奇怪……

所以我把主函数改成:

int main (int args, char** argv) 
{
    std::vector<A> vectA(5);
    std::cout << vectA.capacity() << std::endl; 
}

现在输出是:

destroying A 1
5
destroying A 2
destroying A 3
destroying A 4
destroying A 5
destroying A 6

好的,所以我想当我第一次创建 vectA 时,它获得的分配内存只有一个 A 类型对象的大小,然后它被动态调整大小(作为一个向量的意思)以包含 5 个元素(并且在这个过程之前分配的内存被释放,析构函数被调用)。 所以我的问题是:为什么vectA 没有从一开始就获得适量的内存?毕竟,值 (5) 在编译时是已知的。编译器是否有任何特定原因不执行此优化?

【问题讨论】:

  • 以后请不要使用引号来高亮代码。
  • 好的。只是出于好奇,他们有什么问题?
  • 您无法阅读引号中的代码,因为它只是纯文本,没有突出显示并且格式丢失。我已经修复了它,但仅供将来参考。

标签: c++ vector stl


【解决方案1】:

在 C++11 之前,该代码使用此构造函数,它会生成 countvalue 的副本:

explicit vector(size_type count, const T& value = T(), const Allocator& alloc = Allocator());

一旦 C++11 出现,它就变成了一个构造函数,它只占用一个大小并制作 count 值初始化元素:

explicit vector(size_type count);

因此,在 C++11 之前,您会得到创建的 value 参数,当与五个元素组合时,总共有六个。 C++11之后就只有这五个元素了。

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多