我有这段代码:
#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我第一次创建vectA它获得的分配内存只是A类型的一个对象的大小,然后动态调整大小(作为向量的意思)包含5个元素(并且在此过程中先前分配)内存被释放,析构函数被调用)。 所以我的问题是:为什么vectA从一开始就没有获得正确的内存量? 毕竟,值(5)在编译时已知。 编译器是否有任何特定原因不执行此优化?
I have this piece of code:
#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); }and when I run it I would expect it to print 5 lines (i.e. the destructor is called for each of the 5 elements in the vector) but actually the output is:
destroying A 1 destroying A 2 destroying A 3 destroying A 4 destroying A 5 destroying A 6mmm strange...
so I change the main function to:
int main (int args, char** argv) { std::vector<A> vectA(5); std::cout << vectA.capacity() << std::endl; }and now the output is:
destroying A 1 5 destroying A 2 destroying A 3 destroying A 4 destroying A 5 destroying A 6Ok so I guess when I first create vectA it gets an allocated memory just the size of one object of type A, then it is dynamically resized (as a vector is meant to be) to contain 5 elements (and in this process the previously allocated memory gets freed, and the destructor gets called). So my question is: why doesn't vectA get the right amount memory from the beginning? After all, the value (5) is already known at compile time. Is there any specific reason for the compiler not to perform this optimization?
最满意答案
在C ++ 11之前,该代码使用此构造函数,该构造函数生成value count副本:
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之后,它只是五个元素。
Prior to C++11, that code uses this constructor, which makes count copies of value:
explicit vector(size_type count, const T& value = T(), const Allocator& alloc = Allocator());Once C++11 came around, it got changed to a constructor taking just a size and making count value-initialized elements:
explicit vector(size_type count);Therefore, before C++11, you get the created value parameter, which, when combined with the five elements, makes six total. After C++11, it's just the five elements.
更多推荐
发布评论