Search code examples
c++processmessage-passing

Does C++ let a program compiled by itself to return pointer to an array to be used directly?


For example, if I have some code string like this:

std::string code = R"( 
   #include<thread>
   #include<iostream>
   int main() 
   { 
       int array[@@size@@]; 
       std::cout<<(size_t)&array[0]<<std::endl;
       std::this_thread::sleep(1000000000);
       return 0; 
   } 
)";

boost::replace_all(code, "@@size@@", std::to_string(memSize));

then if I save it to a file programmatically and compile it like this:

system("g++ code.cpp"); 

then run it and parse its output, can I directly use the address to access the array in any way without getting segfault? Does a process have any way of sharing simple arrays to enable faster messaging or other purposes without using any other APIs?

I mean, does it have an advantage on having more freedom on accessing it if the program is compiled & run by current process, with C++?


Solution

  • As far as C++ is concerned, there may not even be a concept of processes. They are mentioned in the standard, as far as I can tell, only twice.

    Once in a recommendation about lock-free atomics, suggesting that they should also work when shared between processes, and once with regards to possible causes of file system races.

    Anything about actually sharing memory between processes would be operating system dependent, and will therefore likely require some operating system specific API calls.