简体   繁体   中英

Top then Pop Usage

I am new to C++ coming from a Python background. I am currently learning deque and I am getting confused on how to pop the last element and use it.

From cppreference.com it mentions that pop_back would remove the last element of the container and the references to the erased element in invalidated.

Example:

std::deque<int> numbers = {1, 2, 3};
int topNumber = numbers.back(); // Return reference to top element
numbers.pop_back(); // remove the last element and now topNumber reference is invalidates

Question: how is it possible to use the top element after popping it? Does.back() return a copy in the example above, and if so why?

Does.back() return a copy in the example above

No, back() return a reference to the last value in the queue.

int topNumber = numbers.back();

The reference is assigned to an int . This effectively copies the referenced object into a completely different and unrelated object called topNumber .

When a reference to some object gets assigned to something else, that not itself a reference, a copy of the referenced object gets made, that's how C++ works (and if it's assigned to a reference, the copy is made into the assigned-to referenced object).

From that point on, the last value in the deque can be removed. It will be gone. But its copy still remains in topNumber .

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