堆栈有一个异常安全的方法返回和删除顶部元素与移动语义? [英] Can a stack have an exception safe method for returning and removing the top element with move semantics?

查看:175
本文介绍了堆栈有一个异常安全的方法返回和删除顶部元素与移动语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答 std :: stack :: pop() 我声称原因 pop 不返回值是为异常安全原因如果复制构造函数throws会发生什么)。

In an answer to a question about std::stack::pop() I claimed that the reason pop does not return the value is for exception safety reason (what happens if the copy constructor throws).

@Konrad 评论说,现在使用移动语义不再相关。这是真的吗?

@Konrad commented that now with move semantics this is no longer relevant. Is this true?

AFAIK,移动构造函数 可以 throw ,但也许可以使用 noexcept 它仍然可以实现。

AFAIK, move constructors can throw, but perhaps with noexcept it can still be achieved.

对于奖励点,这个操作提供什么线程安全保证?

For bonus points what thread safety guarantees can this operation supply?

推荐答案

当然,并不是每个类型都是move-enabled,C ++ 0x甚至允许抛出移动构造函数。只要构造对象从一个右值可能会抛出它不能异常安全。但是,move语义允许你有许多类型,在给定一个右值来源是不可构造的。

Of course, not every type is move-enabled and C++0x even allows throwing move constructors. As long as constructing the object from an rvalue may throw it cannot be exception-safe. However, move semantics allows you to have many types that are nothrow-constructible given an rvalue source.

有条件支持可以使用SFINAE。但是即使没有这样的条件成员函数,也不会阻止你写:

Conditional support for this could be done with SFINAE. But even without such a conditional member function nothing stops you from writing:

auto stack = ...;
auto elem = std::move_if_noexcept(stack.back());
stack.pop_back();

这是强大的异常保证,即使你的移动构造函数不给出强的保证。

which is makes the strong exception guarantee even in case your move constructor doesn't give the strong guarantee.

这篇关于堆栈有一个异常安全的方法返回和删除顶部元素与移动语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆