Reputation: 2767
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:
const static
modifiers do to an instance of a class?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
Upvotes: 0
Views: 1491
Reputation: 51870
Static variables are not shared between processes. Each process gets its own data segment, which is where variables are placed. It doesn't matter whether they're const
or not.
About the const_cast
, you seem to be confused about what it's actually there for. It is able to remove the const
attribute from any variable. The whole point of it is to get the compiler to allow writing to a const
variable. You can use it on anything, and you do so at your own risk. If you strip the const
from something that really isn't writable, you're into undefined behavior.
A const static
variable has the usual meaning. It's static, and it's constant. The type doesn't matter; const static int
or const static A
. Means the same thing for both.
If you want to share the object between processes, then you will need to put it into POSIX shared memory and synchronize access to it. You use shm_open() for this. There are some tutorials on shared memory online, like this one for example.
Upvotes: 3