Joe*_*der 5 c++ queue pointers
假设我有一个整数队列,
#include <iostream>
#include <queue>
using namespace std;
int main() {
int firstValToBePushed = 1;
queue<int> CheckoutLine;
CheckoutLine.push(firstValeToBePushed);
cout << CheckoutLine.front();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用保存指向整数的指针而不是像上面当前那样的整数来完成基本上相同的事情。我计划创建一个循环来生成多个值,但这只是一个更简单的示例。
谢谢,
小智 5
如果这是为了生命周期管理,那么:
std::queue<std::shared_ptr<int>> CheckoutLine;
CheckoutLine.push(std::make_shared<int>(firstValeToBePushed))
Run Code Online (Sandbox Code Playgroud)
如果您的队列类似于代理,并且其他人实际上拥有对象的生命周期,那么绝对可以:
std::queue<std::reference_wrapper<int>> CheckoutLine;
CheckoutLine.push(firstValeToBePushed)
Run Code Online (Sandbox Code Playgroud)
如果您不在任何地方公开队列并且它是内部的,那么存储指针就可以了,正如其他人所建议的那样。
但是,永远不要向客户端公开指针集合,这是最糟糕的事情,因为您将管理生命周期的负担留给了它们,这对集合来说是更混乱的。
当然对于原始类型或者POD来说,只需要复制就可以了,不需要存储指针。移动语义甚至对于非 POD 来说也很容易,除非您有一些棘手的构造或者您反对无法实现移动语义。
#include <functional>为了std::reference_wrapper,#include <memory>为了std::shared_ptr,std::unique_ptr还有朋友。我假设您可以使用现代编译器。
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int value = 1337;
int* firstValeToBePushed = &value;
queue<int*> CheckoutLine;
CheckoutLine.push(firstValeToBePushed);
cout << *(CheckoutLine.front()) << "is at " << CheckoutLine.front();
return 0;
}
Run Code Online (Sandbox Code Playgroud)