I've come across this stack overflow answer which suggests two ways of handling static string class members: https://stackoverflow.com/a/1563906
Defining in cpp file
// a.h
class A {
private:
static const string RECTANGLE;
};
// a.cpp
const string A::RECTANGLE = "rectangle";
Inlining
// a.h
class A {
private:
inline static const string RECTANGLE = "rectangle";
};
I've tried the inline approach and noticed the string is duplicated in every translation unit which imported the header file, and the executable has multiple duplicates.
So, why would anyone prefer the inlining approach if it increases the executable size?
Test setup I've used:
// a.h
#pragma once
class A {
public:
void f();
};
// a.cpp
#include <iostream>
#include "a.h"
#include "b.h" // for no reason
void A::f() {
std::cout << "A" << std::endl;
}
// b.h
#pragma once
#include <string>
class B {
public:
void f();
private:
inline static const std::string STR = "JOHNWICK";
};
// b.cpp
#include <iostream>
#include "b.h"
void B::f() {
std::cout << "B" << std::endl;
}
// main.cpp
#include <iostream>
#include "a.h"
#include "b.h"
int main() {
A a;
B b;
a.f();
b.f();
return 0;
}
Compile: g++ main.cpp a.cpp b.cpp
strings a.out | grep "JOHNWICK"
prints JOHNWICK <3 times>