std::size() and sizeof()

i wanna ask, why std::size() and sizeof() results for array is different while std::size() is said as sizeof()'s replacement..?
e.g.:

1
2
std::array <int, 3> num {1, 2, 9};
std::cout << std::size(num); //result: 3 


using sizeof():
1
2
std::array <int, 3> num {1, 2, 9};
std::cout << sizeof (num); //result: 12 
std::size does not replace sizeof.

The former gives the number of elements in a container.
The latter gives the compile-time constant size of a type or object in bytes.
ic... looks like i was mistakenly took them has the same functions...
i wanna ask also, if num is std::vector why sizeof(num) is 16..?
Because sizeof(a vector) means how much space the vector itself needs(which means, not related to the elements). The vector may holds a pointer that is 8 bytes long, and two ints that are 4*2=8bytes long.
which means, not related to the elements


@point: so you mean, it doesn't matter what type vector object is, the size always 4 bytes?
it doesn't matter what type vector object is, the size always 4 bytes?

Should be easy enough to test (VS 2019, x86 32-bit) Release compile):
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>

int main()
{
   std::vector<char>   cVec { 'a', 'B', 'z' };
   std::vector<double> dVec { 1.0, 2.3, 3.4 };

   std::cout << sizeof(cVec) << ' ' << sizeof(dVec) << '\n';
}
12 12

x86 Debug compile:
16 16

x64 Release compile:
24 24

x64 Debug compile:
32 32

Well, not ALWAYS 4 bytes, but there is a definite pattern that shows the sizeof a vector doesn't matter what the POD data type is. The bitness and type of compile makes a difference.

Just for giggles what about a simple C++ class? What is the sizeof that? (x86 Release)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

class Test
{
public:
    Test() {};
   ~Test() {};

private:
   char data { 0 };
};

int main()
{
   Test t;
   std::cout << sizeof(t) << '\n';

   std::vector<Test> cVec;

   for (size_t i{ }; i < 3; ++i)
   {
      cVec.emplace_back(Test{});
   }

   std::cout << sizeof(cVec) << '\n';
}
1
12
so you mean, it doesn't matter what type vector object is, the size always 4 bytes?
The size is implementation dependent. That means it might be one value for one template type/compiler/operating system and a different value on another. You can't rely on it being anything specific.
ok, thanks for the answers, guys... i'll call it done, then...
Topic archived. No new replies allowed.