Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 意外的C++;队列行为,在弹出后丢失对象_C++ - Fatal编程技术网

C++ 意外的C++;队列行为,在弹出后丢失对象

C++ 意外的C++;队列行为,在弹出后丢失对象,c++,C++,队列的行为不符合预期。在pop()之后,我似乎无法访问对向量的引用 问题: 上述示例是否有代码气味?我是否总是希望在pop()之后丢失引用?我是否应该永远不要在pop()之后使用引用 还是vector是一种特殊情况 EDIT:知道悬挂引用总是不好的做法。我对代码做了一些更改,现在有一些后续问题。 跟进问题: queue<int> q = {}; q.push(1); q.push(2); // making a copy here // follow up question 1: i

队列
的行为不符合预期。在
pop()
之后,我似乎无法访问对
向量的引用

问题:

上述示例是否有代码气味?我是否总是希望在
pop()
之后丢失引用?我是否应该永远不要在
pop()
之后使用引用

还是
vector
是一种特殊情况

EDIT:知道悬挂引用总是不好的做法。我对代码做了一些更改,现在有一些后续问题。

跟进问题:

queue<int> q = {};
q.push(1);
q.push(2);
// making a copy here
// follow up question 1: is this now correct?
int test = q.front();
q.pop();


vector<int> v1 = {0,1,2};
vector<int> v2 = {2,3,4};

queue<vector<int>> q3 = {};

q3.push(v1);
q3.push(v2);

// I am trying to make a copy here but the compiler complains:
// Parameter type mismatch: expression must be rvalue
// follow up question 2: why can't I make a copy of the vector but I can make a copy of the int in the previous example?
vector<int> test3 = q3.front();
q3.pop()
队列q={};
q、 推(1);
q、 推(2);
//在这里复印
//后续问题1:现在是否正确?
int test=q.front();
q、 pop();
向量v1={0,1,2};
向量v2={2,3,4};
队列q3={};
q3.推力(v1);
q3.推送(v2);
//我试图在此处复制,但编译器抱怨:
//参数类型不匹配:表达式必须为右值
//后续问题2:为什么我不能复制向量,但我可以复制上一个例子中的int?
向量test3=q3.front();
q3.pop()

您正在存储对对象的引用,然后销毁该对象。一旦
pop
it退出队列,它就不再在队列中。制作对象的副本,或者在完成操作之前不要弹出它


同样,永远不要尝试访问不再存在的对象。结果将是不可预测的。

当然,您正在失去参考。在
pop()
之后,对队列开头前一个元素的引用现在是对never-land的悬空引用,使用它是教科书上未定义的行为。你到底不清楚什么?你应该针对新问题发布一个新问题,而不是不断地扩展同一个问题。如果您这样做了,发布一个MCVESo,这意味着即使队列示例也是错误的?这只是因为它没有定义行为,所以我还是设法找到了我在
test1
中寻找的int?你不可能在
test1
中找到你正在寻找的int,因为
int
已经不存在了。您可能碰巧看到了您所期望的价值。但这和发生的事情一样,都是你期望的意外。(为什么希望值保持不变?@samol:是的,即使是
队列
示例也是错误的。我意识到我的问题是多么愚蠢。谢谢你对我有耐心。我添加了2个后续问题。您能帮助回答后续问题吗?您的第一个后续问题的答案是“是”。您的第二个后续问题的答案是,您可能在做一些愚蠢的事情,因为代码对我来说应该可以编译和编译/运行。
test1 1 expect: 1
test2 node a expect: node b
test3 size 3 expect: size 3
test4 size 0 expect: size 4

Process finished with exit code 0
queue<int> q = {};
q.push(1);
q.push(2);
// making a copy here
// follow up question 1: is this now correct?
int test = q.front();
q.pop();


vector<int> v1 = {0,1,2};
vector<int> v2 = {2,3,4};

queue<vector<int>> q3 = {};

q3.push(v1);
q3.push(v2);

// I am trying to make a copy here but the compiler complains:
// Parameter type mismatch: expression must be rvalue
// follow up question 2: why can't I make a copy of the vector but I can make a copy of the int in the previous example?
vector<int> test3 = q3.front();
q3.pop()