简体   繁体   中英

References and variable names in C++ - how do they work in regards to memory allocation?

This is a multi part question based on a project I'm currently undertaking. I will try to make it as brief as possible while still fully explaining the question, so sorry if this is a bit long.

  1. When it comes to std::vector s in C++, how exactly do they work with variables? For example, if I have the following code:
int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);

what happens? Does that area of memory inside myIntVector now have the same value of data stored inside myInt at the time of adding, but still completely separate them? Does the area of memory where myInt is stored get physically moved into a designated area inside of the memory of myIntVector ?

  1. Assuming I was correct on the last statement, why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?

  2. Now, for what prompted the question: the #define directive. I was experimenting with this for my project, and noticed something interesting. I used #define GET_NAME(variable) (#variable) , which returns the name of the inputted variable as a character array. If I were to have the following code:

#define GET_NAME(variable) (#variable)

int myInt = 4;
std::vector<int> myIntVector;
myIntVector.push_back(myInt);

std::cout << GET_NAME(myInt) << "\n";
std::cout << GET_NAME(myIntVector[0]);

I would receive the following output:

myInt
myIntVector[0]

Why? Assuming the first statement from question 1 is correct, this is the expected output, but then we circle back to question 2. Assuming the second statement from question 2 is correct, this is the unintended output, as myInt or myIntVector[0] should be returned twice.

Thanks in advance!

When it comes to std::vectors in C++, how exactly do they work with variables?

All STL containers just copy values by default. So when you pass an int variable, it gets copied and the copy exist completely independently from the original value

why would std::cout << myInt still correctly print 4, assuming it was not changed, while std::cout << myIntVector[0] also prints out 4?

These are two different values, both equal to 4

If I were to have the following code, I would receive the following output. Why?

The macros just manipulate the text, and don't do anything fancy in your code. This statement:

std::cout << GET_NAME(myInt) << "\n";

Just turns into this under the macro:

std::cout << "myInt" << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM