C++ dll heap memory allocation issue - c++

From this link, I know that we(application) should always don't delete a heap memory allocation from dll, because the heap memory manager are different.
I have few questions:
1.) How about .so file (Linux), is it the same case ?
2.) Is there anyway to make sure that application and library(.dll and .so) are using same heap memory manager or using same heap memory section ? So we can delete and new separately (new at .dll/.so, delete at application ).
Thank you.

1.) How about .so file (Linux), is it the same case ?
Yes, a library built using a different implementation of the Standard C++ Library than the program it's finally linked with may do allocations in a slightly different manner. g++'s libstdc++ and clang++'s libc++ are examples of two different implementations. They may be 100% ABI compatible - but a third unknown library may not be.
2.) Is there anyway to make sure that application and library(.dll and .so) are using same heap memory manager or using same heap memory section ? So we can delete and new separately (new at .dll/.so, delete at application ).
No, what's compiled into the library is what will be used by the library, unless there's a way to initialize the library upon loading it, telling it to use a specific heap manager.
Please explain in details. I wish to know for .so (Linux), is it using only one heap manager for both application and .so (library). Let's said, my application compiled by compiler version A, while my .so complied by compiler version B, is it still ok ?
Because of the reason mentioned above, no, you can't be sure. Since you are the library creator you could however make your API so that the new and delete memory allocations/deallocations for types in your library are delegated to member functions compiled into the library, which in turn does the real allocations/deallocations (described in operator new, operator new[]
and operator delete, operator delete[]). Pointers to objects of your types could then be newed and passed between the library and application and be deleted on either side.
Here's an (incomplete) example of how that could look using a class-specific allocation function:
void* T::operator new(std::size_t count);
and a class-specific usual deallocation function:
void T::operator delete(void* ptr);
It contains foo.hpp and foo.cpp used to create libfoo.so (or libfoo.a) and code for a program using the library.
foo.hpp
#pragma once
#include <new>
class Foo {
public:
// The "usual" part of your class definition:
Foo(int x);
~Foo();
// This part does NOT get compiled into your library.
// It'll only be used by users of your library:
#ifndef BUILDING_LIB
// Note: operator new and delete are static by default
// single object allocation/deallocation:
void* operator new(std::size_t /* byte_count */) { return Alloc(); }
void operator delete(void* addr) { Free(addr); }
// array allocation/deallocation:
// TODO: operator new[] and delete[]
#endif
private:
int value;
// the functions really doing the memory management
static void* Alloc();
static void Free(void* p);
};
foo.cpp
// Define BUILDING_LIB to disable the proxy operator new/delete functions when building
// the library.
#define BUILDING_LIB
#include "foo.hpp"
#include <cstdlib> // std::aligned_alloc
#include <iostream>
Foo::Foo(int x) : value(x) {
std::cout << "Foo:Foo(" << value << ")\n";
}
Foo::~Foo() {
std::cout << "Foo:~Foo() " << value << "\n";
}
void* Foo::Alloc() {
void* addr = std::aligned_alloc(alignof(Foo), sizeof(Foo));
std::cout << "Alloc() " << sizeof(Foo) << "\t# " << addr << '\n';
return addr;
}
void Foo::Free(void* addr) {
std::cout << "Free()\t\t# " << addr << '\n';
std::free(addr);
}
uselib.cpp
#include "foo.hpp"
#include <memory>
int main() {
auto a = std::make_unique<Foo>(123); // heap allocation
// An automatic variable will use the applications memory manager and will not
// use Alloc/Free.
Foo b(456);
}
Possible output:
Alloc() 4 # 0x1af7eb0
Foo:Foo(123)
Foo:Foo(456)
Foo:~Foo() 456
Foo:~Foo() 123
Free() # 0x1af7eb0

1) Symbol tables are shared across an entire process in Linux. malloc() for any part of the
process is the same as all the other parts. So yes, if all parts of a process access the
heap via malloc() et alia then they will share the same heap.
2) but second question i too have bit confusion.

The heap manager is located in static memory of the runtime library (msvcrXXX for Win and crt for Linux). You can use the runtime library in two ways: as static or dynamic. If you link the runtime as static to your own library, then you can't alloc in your library and free in another. But you link the runtime as dynamic, then you can alloc in your library and free in another.

Library developers take care about this by implementing they own methods for freeing memory allocated inside of library.
For example:
OpenIPMI calls ipmi_fru_node_get_field and ipmi_fru_data_free.
CryptoAPI calls CertCreateCertificateContext and CertFreeCertificateContext

Related

Persist C++ class instance through Matlab mex function calls

Currently trying to figure out how to solve this problem.
Right now I am trying to create mex functions for a C++ library which talks to a microcontroller over serial ports on a Windows 10 PC so that I can call functions in that library in matlab. I am currently working through how to persist an instance of my class through multiple matlab mexFunction calls.
So far the only thing I could come up with is to write a wrapper around the class, declare a global extern unique pointer to my class instance, and include it in my mexFunction() files.
Can anyone tell me if this might work, and if so, how exactly does matlab/C++ handle the mexFunction files and their method calls? The scope of my class instance is what I'm unsure of.
A concrete example might be...
What would happen if I declared an extern unique pointer to an object in a .cpp file and included it in my mexFunction files? Would the pointer stay in scope throughout the matlab script that calls multiple different mexFunctions that manipulate that object?
If I need to rephrase the question or provide more information, please let me know.
Yes, you can do this. If the MEX-files all link to the same shared library (DLL), then they all have access to global variables defined in it. You would need to define your global object in the shared library, not in one of the MEX-files.
MEX-files stay loaded in memory after first execution, until you call clear functions (or clear all). The global object will be destructed when the shared object is cleared from memory. To prevent undesired clearing of your state, you can lock one of the MEX-files in memory using mexLock. I would recommend having one ‘initialize` MEX-file, that constructs the object and locks itself in memory. With a special parameter you can make it unlock itself and destroy the object.
Here is an example:
libXYZ.dylib / libXYZ.so / XYZ.dll -- a shared library, contains a std::shared_ptr<XYZ>.
XYZ_set.mex... -- a MEX-file that initializes the XYZ object, and locks itself in memory. Links to the libXYZ shared library.
XYZ_get.mex... -- another MEX-file that links to the libXYZ shared library and accesses the XYZ object created by the other MEX-file.
XYZ_lib.h:
#include <memory>
#include <iostream>
struct XYZ {
XYZ(double a);
~XYZ();
double get();
private:
double a_;
};
extern std::unique_ptr<XYZ> XYZ_data;
XYZ_lib.cpp:
#include "XYZ_lib.h"
std::unique_ptr<XYZ> XYZ_data;
XYZ::XYZ(double a) : a_(a) {
std::cout << "Constructing XYZ with " << a_ << '\n';
}
XYZ::~XYZ() {
std::cout << "Destructing XYZ, value was " << a_ << '\n';
}
double XYZ::get() {
return a_;
}
XYZ_set.cpp:
#include "XYZ_lib.h"
#include <mex.h>
/// \brief An output stream buffer for MEX-files.
///
/// Creating an object of this class replaces the stream buffer in `std::cout` with the newly
/// created object. This buffer will be used as long as the object exists. When the object
/// is destroyed (which happens automatically when it goes out of scope), the original
/// stream buffer is replaced.
///
/// Create an object of this class at the beginning of any MEX-file that uses `std::cout` to
/// print information to the *MATLAB* terminal.
class streambuf : public std::streambuf {
public:
streambuf() {
stdoutbuf = std::cout.rdbuf( this );
}
~streambuf() {
std::cout.rdbuf( stdoutbuf );
}
protected:
virtual std::streamsize xsputn( const char* s, std::streamsize n ) override {
mexPrintf( "%.*s", n, s );
return n;
}
virtual int overflow( int c = EOF ) override {
if( c != EOF ) {
mexPrintf( "%.1s", &c );
}
return 1;
}
private:
std::streambuf* stdoutbuf;
};
void mexFunction( int, mxArray*[], int nrhs, const mxArray* prhs[] ) {
streambuf buf; // Allows std::cout to work in MEX-files
// Always do lots of testing for correct input in MEX-files!
if (nrhs!=1) {
mexErrMsgTxt("Requires 1 input");
}
if (mxIsChar(prhs[0])) {
// Assume it's "-unlock" or something like that. Unlock MEX-file
mexUnlock();
std::cout << "XYZ can now be cleared from memory\n";
} else {
// Here we create new data
if (!mxIsDouble(prhs[0]) || mxIsEmpty(prhs[0])) {
mexErrMsgTxt("Expected double input");
}
double a = *mxGetPr(prhs[0]);
XYZ_data = std::unique_ptr<XYZ>(new XYZ(a));
// If the MEX-file is not locked, lock it
if (!mexIsLocked()) {
mexLock();
}
}
}
(Sorry for the streambuf class here, it's noise, but I wanted to use it so you can see the constructor and destructor in the shared library being called.)
XYZ_get.cpp:
#include "XYZ_lib.h"
#include <mex.h>
void mexFunction( int, mxArray* plhs[], int, const mxArray* [] ) {
if (XYZ_data) {
plhs[0] = mxCreateDoubleScalar(XYZ_data->get());
} else {
mexErrMsgTxt("XYZ not initialized!");
}
}
Compiling:
In a shell (I'm using MacOS, hence the dylib extension, adjust as necessary):
g++ -std=c++11 -Wall -fpic XYZ_lib.cpp -shared -o libXYZ.dylib
In MATLAB:
mex XYZ_set.cpp libXYZ.dylib
mex XYZ_get.cpp libXYZ.dylib
Running:
>> XYZ_get
Error using XYZ_get
XYZ not initialized!
>> XYZ_set(4)
Constructing XYZ with 4
>> XYZ_set(6)
Constructing XYZ with 6
Destructing XYZ, value was 4
>> XYZ_get
ans =
6
>> clear all
>> XYZ_set -unlock
XYZ can now be cleared from memory
>> clear all
Destructing XYZ, value was 6
As you can see, XYZ_get accesses the value in an object that was newed by XYZ_set. clear all typically clears everything from memory, but here the locked MEX-file stays. XYZ_set -unlock calls it with a string argument, which causes it to unlock itself. clear all now clears that MEX-file from memory also, and now the XYZ object is destroyed.
I need to mention here that C++ doesn't have a consistent ABI, and these MEX-files will only load if the shared library was compiled with the same compiler.
An alternative, and often simpler, is to create only one single MEX-file (statically linked with your C++ code), and a bunch of M-files that call the MEX-file. The M-files provide the nice interface (can do input checking also), and the MEX-file sits in a private/ directory where nobody can mess with it. The MEX-file can still do the locking thing, so it can hold on to objects that are preserved from call to call.

Testing for proper behaviour on memory allocation failures

We have a relatively large code base for a Linux server, it's dynamically linked-in libraries and server modules loaded during startup using dlopen(). The server as well as most of the other components are written in C++11, but some are in C99.
What approaches could one use to test whether the server, its dependencies and modules properly handle memory allocation failures, e.g.malloc/calloc returning NULL, operators new and new[] throwing std::bad_alloc etc, including allocation failures from std::string::resize() and such?
In the past, I've tried using memory allocation hooks to inject memory allocation failures into C applications, but I think these don't work for C++. What other options or approaches should I be looking at?
In fact, hooking into C malloc is enough, since under the hood the gcc C++ default implementation of operator new does call malloc and you confirmed you only needed a gcc compatible solution.
I could demonstrate it with that simple program:
mem.c++:
#include <iostream>
#include <string>
class A {
int ival;
std::string str;
public:
A(int i, std::string s): ival(i), str(s) {}
A(): ival(0), str("") {};
int getIval() const {
return ival;
}
std::string getStr() const {
return str;
}
};
int main() {
A a(2, "foo");
std::cout << &a << " : " << a.getIval() << " - " << a.getStr() << std::endl;
return 0;
}
memhook.c:
#include <stdio.h>
#include <stdlib.h>
extern void *__libc_malloc(size_t size);
void* malloc (size_t size) {
fprintf(stderr, "Allocating %u\n", size);
return NULL;
// return __libc_malloc(size);
}
When returning NULL (as above), the program displays:
Allocating 16
Allocating 100
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Abandon (core dumped)
That proves that returning NULL from the declared malloc function results in a std::bad_alloc exception in C++ code
When uncommenting the return __libc_malloc(size); the allocations are done by the libc malloc and the output becomes:
Allocating 16
0xbfe8d2e8 : 2 - foo
On linux you can hook into the operating system to force allocation to fail
man 2 mlockall
mlockall(MCL_CURRENT|MCL_FUTURE);
Should do what you want.

Import C++ member function at run-time with Gcc

Problem
I am currently working on a plugin-library, where one should be able to not only import C-Linkage symbols, but all imported things.
Thus far it works, though the problem is, that gcc screws member-function calls up.
If I export the following:
static member_function(Class* c)
{ c->method();}
it works fine an I can access the class-members. But if I do the following:
void (Class ::*p)() = import("Class::method");
(x.*p)();
i get the right pointer and also am able to call the function and the passed arguments, but the this pointer is pointing into nirvana. I think gcc is taking it from the wrong position of the stack or something like that.
It works just fine with MSVC.
I am using mingw-w64 5.1.
Does anyone have an idea what the error could be?
Simple example:
plugin.cpp
#include <iostream>
namespace space {
class __declspec(dllexport) SomeExportThingy
{
int i = 42;
public:
virtual void __declspec(dllexport) Method(int*) const
{
using namespace std;
cout << "Calling Method" << endl;
cout << pi << endl;
cout << *pi << endl;
cout << this << endl;
cout << this->i << endl;
}
}
}
loader.cpp
namespace space {
class SomeExportThingy
{
///dummy to have some data in the address
int dummy[20];
};
int main()
{
auto h = LoadLibrary("plugin.dll");
auto p = GetProcAddress(h, "_ZNK5space16SomeExportThingy6MethodEPi");
typedef void (space::SomeExportThingy::*mptr)(int*) const;
///used because posix passed void*
auto fp = *reinterpret_cast<mptr*>(&p);
space::SomeExportThingy st;
int value = 22;
cout << "ValueLoc: " << &value << endl;
cout << "StLoc: " << &st << endl;
(st.*fp)(&value);
}
Results
Now what happens is, that the function is called and the pointer to pi is passed correctly. However, the this pointer is completly screwed up.
Again: it works with MSVC, which get's the this pointer correctly, but gcc get's this wrong.
I have no idea why this happens, and removing the virtual from the method doesn't change that either.
I have no idea what causes this, so maybe someone has an idea what the ABI is doing here.
Here are the pointers I am getting:
0x00400000 == GetModuleHandleA(NULL)
0x61840000 == GetModuleHandleA("plugin.dll")
0x0029fcc4 == _&st
0x00ddcd60 == this
I wasn't able to find any relation between the values
This is not going to work with GCC:
typedef void (space::SomeExportThingy::*mptr)(int*) const;
///used because posix passed void*
auto fp = *reinterpret_cast<mptr*>(&p);
The representation of a pointer-to-member is twice the size of a normal function pointer (or a void*) so you are reading two words from a memory location that only contains one word. The second word (which tells the compiler how to adjust the this pointer for the call) is garbage, it is just whatever happens to be after p on the stack.
See https://gcc.gnu.org/onlinedocs/gcc/Bound-member-functions.html:
In C++, pointer to member functions (PMFs) are implemented using a wide pointer of sorts to handle all the possible call mechanisms; the PMF needs to store information about how to adjust the ‘this’ pointer,
p is a void* so it's a memory location on the stack that occupies sizeof(void*) bytes.
&p is a pointer to that memory location.
reinterpret_cast<mptr*>(&p) is a pointer to 2*sizeof(void*) bytes at the same address.
*reinterpret_cast<mptr*>(&p) reads 2*sizeof(void*) bytes from a memory location that is only sizeof(void*) bytes in size.
Bad things happen.
For linux, the functions for dynamic function loading are: dlopen(), dlsym(), and dlclose(). Please reference: dlopen() man page.
Consider that C++ method names are 'mangled' and and they have an invisible '*this' parameter passed before all the others. Together both issues makes trying to directly access C++ objects not trivial when using dynamic linking.
The easiest solution I've found is to use 'C' function(s) that expose access to the C++ object instance.
Secondly, memory management of C++ objects is not trivial when the code to instantiate is within an .so library object, though the referencing code is from the user's app.
For the long answer as to why avoiding Pointer to C++ Member Methods is difficult, please reference: ISO CPP Reference, Pointers to Methods.
/** File: MyClass.h **/
// Explicitly ensure 'MyClassLoaderFunc' is NOT name mangled.
extern 'C' MyClass* MyClassLoaderFunc(p1, p2 ,p3, etc );
extern 'C' MyClass* MyClassDestroyerFunc(MyClass* p);
// Create function pointer typedef named 'LoaderFuncPtr'
typedef MyClass*(MyClassLoaderFunc* LoaderFuncPtr)(p1,p2,p3,etc);
// Define MyClass
class MyClass
{
/** methods & members for the class go here **/
char dummy[25];
int method( const char *data);
};
/** File: MyClass.cpp **/
#include "MyClass.h"
MyClass* MyLoaderFunc(p1, p2 ,p3, etc) {
MyClass* newInstance = new MyClass::CreateInstance( p1, p2, p3, etc);
/** Do something with newInstance **/
return newInstance;
}
MyClass::method(const char* data)
{
}
/** File: MyProgram.cpp **/
#include "MyClass.h"
main()
{
// Dynamically load in the library containing the object's code.
void *myClassLibrary = dlopen("path/to/MyClass.so",RTLD_LOCAL);
// Dynamically resolve the unmangled 'C' function name that
// provides the bootstrap access to the MyClass*
LoaderFuncPtr loaderPtr = dlsym(myClassLibrary,"MyClassLoaderFunc");
DestroyFuncPtr destroyerPtr = dlsym(myClassLibrary,"MyClassDestroyerFunc");
// Use dynamic function to retrieve an instance of MyClass.
MyClass* myClassPtr = loadPtr(p1,p2,p3,etc);
// Do something with MyClass
myClassPtr->method();
// Cleanup of object should happen within original .cpp file
destroyPtr(myClassPtr);
myClassPtr = NULL;
// Release resources
dlclose(myClassLibrary);
return 0;
}
Hope this helps..
I also suggest a factory paradigm as an more robust solution, that I'll leave to the reader to explore.
As Jonathan pointed out, pointer-to-members are bigger than normal function pointers.
The simplest solution is to reserve and initialize the extra space.
typedef void (space::SomeExportThingy::*mptr)(int*) const;
union {
mptr fp;
struct {
FARPROC function;
size_t offset;
};
} combFp;
combFp.function = p;
combFp.offset = 0;
auto fp = combFp.fp;

In C++, how can I get the current thread's call stack?

I'm writing this error handler for some code I'm working in, in C++. I would like to be able to make some sort of reference to whatever I have on the stack, without it being explicitly passed to me. Specifically, let's say I want to print the names of the functions on the call stack, in order. This is trivial in managed runtime environments like the JVM, probably not so trivial with 'simple' compiled code. Can I do this?
Notes:
Assume for simplicity that I compile my code with debugging information and no optimization.
I want to write something that is either platform-independent or multi-platform. Much prefer the former.
If you think I'm trying to reinvent the wheel, just link to the source of the relevant wheel and I'll look there.
Update:
I can't believe how much you need to bend over backwards to do this... almost makes me pine for another language which shall not be mentioned.
There is a way to get a back-trace in C++, though it is not portable. I cannot speak for Windows, but on Unix-like systems there is a backtrace API that consists primarily of the following functions:
int backtrace(void** array, int size);
char** backtrace_symbols(void* const* array, int size);
void backtrace_symbols_fd(void* const* array, int size, int fd);
You can find up to date documentation and examples on GNU website here. There are other sources, like this manual page for OS X, etc.
Keep in mind that there are a few problems with getting backtrace using this API. Firstly, there no file names and no line numbers. Secondly, you cannot even get backtrace in certain situations like if the frame pointer is omitted entirely (default behavior of recent GCC compilers for x86_64 platforms). Or maybe the binary doesn't have any debug symbols whatsoever. On some systems, you also have to specify -rdynamic flag when compiling your binary (which has other, possible undesirable, effects).
Unfortunately, there is no built-in way of doing this with the standard C++. You can construct a system of classes to help you build a stack tracer utility, but you would need to put a special macro in each of the methods that you would like to trace.
I've seen it done (and even implemented parts of it) using the strategy outlined below:
Define your own class that stores the information about a stack frame. At the minimum, each node should contain the name of the function being called, file name / line number info being close second.
Stack frame nodes are stored in a linked list, which is reused if it exists, or created if it does not exist
A stack frame is created and added to the list by instantiating a special object. Object's constructor adds the frame node to the list; object's destructor deletes the node from the list.
The same constructor/destructor pair are responsible for creating the list of frames in thread local storage, and deleting the list that it creates
The construction of the special object is handled by a macro. The macro uses special preprocessor tokens to pass function identification and location information to the frame creator object.
Here is a rather skeletal proof-of-concept implementation of this approach:
#include <iostream>
#include <list>
using namespace std;
struct stack_frame {
const char *funName;
const char *fileName;
int line;
stack_frame(const char* func, const char* file, int ln)
: funName(func), fileName(file), line(ln) {}
};
thread_local list<stack_frame> *frames = 0;
struct entry_exit {
bool delFrames;
entry_exit(const char* func, const char* file, int ln) {
if (!frames) {
frames = new list<stack_frame>();
delFrames = true;
} else {
delFrames = false;
}
frames->push_back(stack_frame(func, file, ln));
}
~entry_exit() {
frames ->pop_back();
if (delFrames) {
delete frames;
frames = 0;
}
}
};
void show_stack() {
for (list<stack_frame>::const_iterator i = frames->begin() ; i != frames->end() ; ++i) {
cerr << i->funName << " - " << i->fileName << " (" << i->line << ")" << endl;
}
}
#define FUNCTION_ENTRY entry_exit _entry_exit_(__func__, __FILE__, __LINE__);
void foo() {
FUNCTION_ENTRY;
show_stack();
}
void bar() {
FUNCTION_ENTRY;
foo();
}
void baz() {
FUNCTION_ENTRY;
bar();
}
int main() {
baz();
return 0;
}
The above code compiles with C++11 and prints this:
baz - prog.cpp (52)
bar - prog.cpp (48)
foo - prog.cpp (44)
Functions that do not have that macro would be invisible on the stack. Performance-critical functions should not have such macros.
Here is a demo on ideone.
It is not easy. The exact solution depends very much on the OS and Execution environment.
Printing the stack is usually not that difficult, but finding symbols can be quite tricky, since it usually means reading debug symbols.
An alternative is to use an intrusive approach and add some "where am I" type code to each function (presumably for "debug builds only"):
#ifdef DEBUG
struct StackEntry
{
const char *file;
const char *func;
int line;
StackEntry(const char *f, const char *fn, int ln) : file(f), func(fn), line(ln) {}
};
std::stack<StackEntry> call_stack;
class FuncEntry
{
public:
FuncEntry(const char *file, const char *func, int line)
{
StackEntry se(file, func, line);
call_stack.push_back(se);
}
~FuncEntry()
{
call_stack.pop_back();
}
void DumpStack()
{
for(sp : call_stack)
{
cout << sp->file << ":" << sp->line << ": " << sp->func << "\n";
}
}
};
#define FUNC() FuncEntry(__FILE__, __func__, __LINE__);
#else
#define FUNC()
#endif
void somefunction()
{
FUNC();
... more code here.
}
I have used this technique in the past, but I just typed this code in, it may not compile, but I think it's clear enough . One major benefit is that you don't HAVE to put it in every function - just "important ones". [You could even have different types of FUNC macros that are enabled or disabled based on different levels of debugging].

static const to an object in a shared library in C++. Is it share between processes?

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
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.