I've been writing a shared library in C++, but I want to share some instance of a class through users of the library. I mean, a read-only object loaded just one time from the library and used by every process linked to the library.
As far as I know this can be made using const
or static const
, but it doesn't work as expected.
For example:
#include <iostream>
static const int x = 1;
int main()
{
std::cout << x << std:endl;
*(const_cast<int *>(&x)) = 2;
std::cout << x << std:endl;
return 0;
}
Using GCC 4.8.1 the code compiles well but, obviously, it fails at runtime because the x
variable is read-only (it produces a segmentation fault on my Linux).
However, lets see this code:
#include <iostream>
struct A
{
A() : x(1) {}
int x;
}
static const A a;
int main()
{
std::cout << a.x << std:endl;
const_cast<A *>(&a)->x = 2;
std::cout << x << std:endl;
return 0;
}
The last code compiles and run well. The executable prints
1
2
I was able to modify the const data! So I guess the const modifier does NOT work properly with classes.
Then my questions are:
- What do the
const static
modifiers do to an instance of a class? - How could I put an instance in a shared library to share it through different processes, loading once and sharing the same RAM memory?
The class I want to instantiate inherits from an abstract one. I am using C++11 but codes shown before were tested without the C++11 support.
sorry if I made any english mistake