In C++, the term “stateless” typically refers to a type (class or struct) that:
- Has no non-static data members, meaning it does not store any instance-specific information.
- Does not maintain any internal state or data that varies between objects of that type.
Stateless types are often empty classes used for utility purposes, such as:
Custom deleters for smart pointers.
#include <memory>
#include <iostream>
struct EmptyDeleter {
void operator()(int* ptr) const {
delete ptr;
std::cout << "Deleted\n";
}
};
int main() {
std::unique_ptr<int, EmptyDeleter> ptr(new int(42));
std::cout << "Size of unique_ptr: " << sizeof(ptr) << " bytes\n"; // 8 bytes
return 0;
}
Tags for template metaprogramming.
#include <iostream>
struct TagA {};
struct TagB {};
template<typename Tag>
void choose_tag(Tag tag) {
std::cout << "TAG B!" << std::endl;
}
template<>
void choose_tag(TagA tag) {
std::cout << "TAG A!" << std::endl;
}
int main() {
choose_tag(TagA{}); // TAG A!
choose_tag(TagB{}); // TAG B!
choose_tag(3); // TAG B! -- abuse here
return 0;
}
Functors or lambdas with no captures.
#include <iostream>
int main() {
auto add_one = [](int& x) {x++;};
std::cout << sizeof(add_one) << std::endl; // 1 byte
return 0;
}
The stateless functors, lambdas, and empty deleters are essentially the same thing, but built for different purposes.