I was on a forum just now and came across a basic question that let me to a peculiar result. The question had to do with using c_str() in C++ and an array of const char*
to hold the references. Consider the following code:
#include <iostream>
#include <string>
struct appendable_array{
int newest_item_index = 0;
const char* aarray[10];
};
void append_array(appendable_array& t, const std::string& s){
std::cout << "Assigned \"" << s << "\"" << " index " << t.newest_item_index << std::endl;
t.aarray[t.newest_item_index++] = s.c_str();
}
int main(void) {
struct appendable_array arr;
append_array(arr, std::string("Hello"));
append_array(arr, std::string("There"));
append_array(arr, std::string("World!"));
for(int i = 0; i < 3; i++)
std::cout << arr.aarray[i] << std::endl;
return 0;
}
Where the output results in:
- Assigned "Hello" index 0
- Assigned "There" index 1
- Assigned "World!" index 2
- World!
- World!
- World!
However, if we use unique string objects, shown below, then we get the following output.
int main(void) {
struct appendable_array arr;
std::string str1("Hello");
std::string str2("There");
std::string str3("World!");
append_array(arr, str1);
append_array(arr, str2);
append_array(arr, str3);
for(int i = 0; i < 3; i++)
std::cout << arr.aarray[i] << std::endl;
return 0;
}
- Assigned "Hello" index 0
- Assigned "There" index 1
- Assigned "World!" index 2
- Hello
- there
- World!
So, I was naturally curious to know why each of the original objects pointed to the same memory location. I came to the conclusion that it must have something to do with anonymous run-time objects being created that are shared (I imagine with global scope, but I did not test this). The logic here makes sense, since it is not necessary to create many anonymous objects that do not have explicit references to their location within the code.
tl;dr - How are anonymous objects shared at run-time, and how are the implemented? If I am completely wrong with this being some sort of shared object, how else might the obvious shared memory references be explained?