为什么我可以将大小不同的对象存储在数组中?
Why can I store objects in array that differ in size?
例如下面的代码:
#include <iostream>
#include <vector>
class VectorContainer
{
public:
VectorContainer(std::vector<int>::size_type sz)
{
foo.reserve(sz);
for (int i = 0; i < sz; i++) {
foo.push_back(i);
}
}
std::vector<int> foo;
};
int main(int argc, const char * argv[]) {
VectorContainer containerOne(0);
VectorContainer containerTwo(1);
std::cout << &containerOne << std::endl;
std::cout << &containerTwo << std::endl;
VectorContainer arr[2] = {containerOne, containerTwo};
std::cout << &arr[0] << std::endl;
std::cout << &arr[1] << std::endl;
return 0;
}
产生以下输出:
0x7ffeefbff578
0x7ffeefbff560
0x7ffeefbff5e0
0x7ffeefbff5f8
为什么这里可以将 VectorContainer(大小不同)存储在一个数组中而没有任何负面影响?为什么后两个地址与前两个地址不同?
我还以为containerOne和containerTwo直接躺在数组容器里面,没有任何指针
Why is it here possible to store VectorContainers (that differ in size) in one array without any negative effects?
因为每个 VectorContainer
对象都有相同的 对象表示 占用相同的字节数 sizeof(VectorContainer)
,本质上是 sizeof(std::vector<>)
。关键是矢量本身持有一个 指针 指向不同的内存区域,实际上大小可能不同。但是由于该区域的大小对指针的大小没有影响(因此对矢量对象的表示布局),您可以将这些对象打包到一个公共数组中。
请注意,此技术基本上也是多态性的核心。
And why are the last two addresses differ from the first both ones?
因为它们涉及完全不同的对象。前两个是单独的对象,而后两个是初始化数组时从第一个对象复制的数组的一部分。
例如下面的代码:
#include <iostream>
#include <vector>
class VectorContainer
{
public:
VectorContainer(std::vector<int>::size_type sz)
{
foo.reserve(sz);
for (int i = 0; i < sz; i++) {
foo.push_back(i);
}
}
std::vector<int> foo;
};
int main(int argc, const char * argv[]) {
VectorContainer containerOne(0);
VectorContainer containerTwo(1);
std::cout << &containerOne << std::endl;
std::cout << &containerTwo << std::endl;
VectorContainer arr[2] = {containerOne, containerTwo};
std::cout << &arr[0] << std::endl;
std::cout << &arr[1] << std::endl;
return 0;
}
产生以下输出:
0x7ffeefbff578
0x7ffeefbff560
0x7ffeefbff5e0
0x7ffeefbff5f8
为什么这里可以将 VectorContainer(大小不同)存储在一个数组中而没有任何负面影响?为什么后两个地址与前两个地址不同?
我还以为containerOne和containerTwo直接躺在数组容器里面,没有任何指针
Why is it here possible to store VectorContainers (that differ in size) in one array without any negative effects?
因为每个 VectorContainer
对象都有相同的 对象表示 占用相同的字节数 sizeof(VectorContainer)
,本质上是 sizeof(std::vector<>)
。关键是矢量本身持有一个 指针 指向不同的内存区域,实际上大小可能不同。但是由于该区域的大小对指针的大小没有影响(因此对矢量对象的表示布局),您可以将这些对象打包到一个公共数组中。
请注意,此技术基本上也是多态性的核心。
And why are the last two addresses differ from the first both ones?
因为它们涉及完全不同的对象。前两个是单独的对象,而后两个是初始化数组时从第一个对象复制的数组的一部分。