Question about global variables
I don't understand why this code behaves the way it does. I have a constant pointer included in two files which takes different values in each.
header.h
void file1();
int* const global_ptr = new int;
file1.cpp
#include "header.h"
#include <cstdio>
void file1() {
printf("File 1 ptr: %p\n", global_ptr);
}
file2.cpp
#include "header.h"
#include <cstdio>
void file2() {
printf("File 2 ptr: %p\n", global_ptr);
}
int main() {
file1();
file2();
}
I know the two files have their own copies of global_ptr since it is const but when I run the code you can see they point to different locations:
File 1 ptr: 0x2503030
File 2 ptr: 0x2503010
My best guess is that new gets called separately for each file but your insight (and any ways to work around this) is appreciated.
Posted Jun 22, 2016, 3:50 PM UTC · edited
Not sure what you're end goal here is, apparently a work around would look like this, but you shouldn't do this to begin with. You should declare ptr locally (inside your main using
auto* ptr = make_unique<int>()) and then rewrite your functions to take aconst int*parameter and call them usingfile(ptr.get()). This will properly delete the pointer automatically.If C++11 or boost isn't an option you can do the same using new and delete inside main.