Is sizeof useful in modern C++?

Im just re reading through some material and im wondering, is the sizeof operator useful in modern C++? I could see how it could probably be useful back in the day when data was limited and you needed to know the sizes of things, but nowadays computers have SO much memory that those concerns are pretty much non existent.
It could still be useful for some things (e.g. when writing and reading binary data) but it's a relatively low-level feature and like the bitwise operators it's not at all strange if you don't have a use for them very often.

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 <fstream>
#include <string>

int main()
{
	const std::string filename = "data.bin";
	
	// Write
	{
		std::uint32_t outdata = 123;
		std::ofstream file(filename, std::ios::binary);
		file.write(reinterpret_cast<const char*>(&outdata), sizeof(outdata));
		
		std::cout << "Wrote " << outdata << " to file.\n";
	}
	
	// Read
	{
		
		std::uint32_t indata;
		std::ifstream file(filename, std::ios::binary);
		file.read(reinterpret_cast<char*>(&indata), sizeof(indata));
		
		std::cout << "Read " << indata << " from file.\n";
	}
}
Wrote 123 to file.
Read 123 from file.
Last edited on
Apart from usage in binary data, another common usage of sizeof prior to C++17 was to determine the number of elements in a c-style array. However since C++17 there has been std::size() (and std::ssize() since C++20).

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <iterator>

int main() {
	constexpr int arr[] { 1, 2, 3, 4 };

	std::cout << sizeof arr / sizeof arr[0] << '\n';
	std::cout << std::size(arr) << '\n';
}



4
4



sizeof arr provides the total number of bytes in the arr array and sizeof arr[0] the number of bytes in the first element. Simple division gives the number of elements.


PS.
I could see how it could probably be useful back in the day when data was limited and you needed to know the sizes of things, but nowadays computers have SO much memory that those concerns are pretty much non existent.


sizeof has nothing to do with available memory. It usage is for the size of types and variables.
Last edited on
It is required in some situations; for instance for implementing a custom allocator.
Topic archived. No new replies allowed.