C++ 如何存储queue::front返回的值?

C++ 如何存储queue::front返回的值?,c++,pointers,reference,queue,return-type,C++,Pointers,Reference,Queue,Return Type,我有点不确定如何使用std::queue库中front函数返回的值。在cplusplus.com网站上,它说该函数返回一个引用。 但是,当我查看实际用法时,似乎该函数直接用于获取值 例如,通过以下步骤 std::queue<int> myqueue; myqueue.push(30); 那么这怎么可能呢: std::cout << "myqueue.front() returns " << myqueue.front() //myqueue.front()

我有点不确定如何使用std::queue库中front函数返回的值。在cplusplus.com网站上,它说该函数返回一个引用。 但是,当我查看实际用法时,似乎该函数直接用于获取值

例如,通过以下步骤

std::queue<int> myqueue;
myqueue.push(30);
那么这怎么可能呢:

std::cout << "myqueue.front() returns " << myqueue.front() 
//myqueue.front() returns 30
edfPtr将指向abcPtr也指向的相同位置


如果是这样,那么将std::queue::front返回的值作为引用传递有什么意义呢。有人知道这种用法背后的逻辑吗

它确实会返回一个引用,但与其他情况一样,如果您将引用指定给该类型的普通对象,则会指定引用所引用的对象

int a = 1;
int &ra = a; // reference to a

int b = ra;  // initializes `b` to the value referred to by `ra`--1 in this case.
在front的特定情况下,如果您存储的值很大,您可能希望避免创建它的额外副本。在这种情况下,您可以直接使用该引用,或者使用它初始化另一个引用以获取队列中的值的别名,这样您就可以在不创建副本的情况下使用它

class something_big {
    // lots of data here
};

std::queue<something_big> foo;

something_big bar = foo.front(); // copies entire item from front of queue into bar

something_big &baz = foo.front(); // no copy; just access item in queue

除非必要,否则返回引用的逻辑是避免复制。如果队列中没有整数或指针,而是包含更重的内容,如大型结构或大型向量

int math_on_large_vector(const std::vector<int>& data) {
    // ...
}

std::queue<std::vector<int>> myqueue;
myqueue.emplace(std::vector<int>(10000, 0));
math_on_large_vector(myqueue.front()) // Doesn't copy the entire vector

这对int或指针之类的东西并不重要,但对复制成本很高的东西却很重要。

不要将引用视为指针,而应将其视为别名或同义词。看这个:我明白了。那么这是否意味着这样做&some_int=。。。不会做任何事情来更改某个int指向的位置,但只更改其值?这是否意味着这样做&some int=3不会做任何事情来更改某个int的位置,而只更改其值?这样做&some_ptr=另一个_ptr赋值给指针的引用只会改变某个_ptr指向的位置?这也相当于写一些_ptr=另一个_ptr?
int a = 1;
int &ra = a; // reference to a

int b = ra;  // initializes `b` to the value referred to by `ra`--1 in this case.
class something_big {
    // lots of data here
};

std::queue<something_big> foo;

something_big bar = foo.front(); // copies entire item from front of queue into bar

something_big &baz = foo.front(); // no copy; just access item in queue
int math_on_large_vector(const std::vector<int>& data) {
    // ...
}

std::queue<std::vector<int>> myqueue;
myqueue.emplace(std::vector<int>(10000, 0));
math_on_large_vector(myqueue.front()) // Doesn't copy the entire vector
std::vector<int> local_copy(my_queue.front());
local_copy = my_queue.front();