在Java中,Deque该类具有实际返回返回元素的末尾的删除方法.在C++中,似乎实现相同行为的唯一方法是首先显式复制元素然后弹出它.
std::deque<int> myDeque;
myDeque.push_back(5);
int element = myDeque.back();
myDeque.pop_back();
Run Code Online (Sandbox Code Playgroud)
是否有同时进行这两种机制的机制?
Ker*_* SB 11
您可以编写自己的包装函数模板:
// Precondition: !container.empty()
// Exception safety: If there is an exception during the construction of val,
// the container is not changed.
// If there is an exception during the return of the value,
// the value is lost.
template <typename C>
auto back_popper(C & container) -> decltype(container.back())
{
auto val(std::move(container.back()));
container.pop_back();
return val;
}
Run Code Online (Sandbox Code Playgroud)
用法:
auto element = back_popper(myDeque);
Run Code Online (Sandbox Code Playgroud)
你不能得到解决,激励的分离的根本问题back(),并pop_back()在首位,这是该元素的复制或移动构造函数可能会抛出异常,并且当发生这种情况,你可能会失去在弹出的元素.您可以通过返回非投掷对象(例如a unique_ptr)来逐个缓解它,这会牺牲动态分配丢失元素的风险,但显然这是您必须做出的个人选择标准不适合你.
例如:
// Guarantees that you either get the last element or that the container
// is not changed.
//
template <typename C>
auto expensive_but_lossless_popper(C & container)
-> typename std::unique_ptr<decltype(container.back())>
{
using T = decltype(container.back());
std::unique_ptr<T> p(new T(std::move(container.back())));
container.pop_back();
return p; // noexcept-guaranteed
}
Run Code Online (Sandbox Code Playgroud)
编辑:我std::move在back()@Simple建议的附近添加了调用.这是合法的,因为不再需要move-from元素,并且许多真实世界的类都带有noexcept移动构造函数,因此这涵盖了大量的情况,而"无损"的解决方法只为少数几个提供了优势.没有noexcept动作的"怪异"类型.
Dan*_*rey 10
按照设计,C++不提供开箱即用的机制来确保异常安全:
当您尝试实现它时,首先制作元素的副本,然后弹出容器,最后您要将对象返回给调用者.但是当最后一个操作的复制构造函数抛出异常时会发生什么?对象不再在容器中,并且作为调用者,您没有收到它的副本.为了防止这种情况并为容器的操作提供强大的异常保证,不会直接支持返回同时弹出的元素的操作.
| 归档时间: |
|
| 查看次数: |
420 次 |
| 最近记录: |