堆栈弹出操作是否可以安全地返回 C++11 中的值
Could stack pop operation return the value safely in C++11
因此,在 C++11 中,似乎不再需要如此严格地隔离堆栈中的 .top 和 .pop。
也许我错过了一些东西,但是 C++03 及更早版本中的问题是,如果 .pop 返回一个值,则复制操作可能会在元素复制期间引发异常。 示例(从此处获取的代码示例):
template <class T>
// T must have default ctor and copy assignment
class Stack
{
public:
Stack();
~Stack();
Stack(const Stack&);
Stack& operator=(const Stack&);
unsigned Count(); // returns # of T's in the stack
void Push(const T&);
T Pop(); // if empty, returns default-
// constructed T
T Top(); // For backwards compatibility
//
private:
T* v_; // pointer to a memory area big
// enough for 'vsize_' T objects
unsigned vsize_; // the size of the 'v_' area
unsigned vused_; // the number of T's actually
// used in the 'v_' area
};
如果要执行此操作:
int main(){
Stack<vector<double>> stack;
fill_stack(stack); //fill stack with huge vectors
stack.pop(); //danger of exception being throw from low memory
}
在 C++11 中,这个问题完全消失了,因为元素可以从堆栈中移动,完全消除了异常安全问题。这是在假定该元素是可移动的并且移动操作不会抛出的情况下进行的。
因此,我的问题归结为,如果 .pop 通过移动语义返回元素,是否存在真正的安全异常问题?
在 DyP 的几个指针之后,这段代码应该可以完成我在 OP 中要求的技巧。由于top
通过引用返回,因此可以安全地将其从 -ed 中移出,然后立即pop
-ed。帮助程序函数检查先决条件是否满足(必须是可移动的),并且希望是一个 nothrow 操作:)
template<class T>
T pull_top(std::stack<T>& x) noexcept(std::is_nothrow_move_constructible<T>::value)
{
static_assert(std::is_move_constructible<T>::value, "pull_top requires the type to be move constructible");
T val = std::move(x.top());
x.pop();
return val;
}
相关文章:
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 为什么 c++11 std::normal_distribution 在从函数调用时返回相同的模式?
- 在 C++11 函数中使用尾随返回类型的优点
- 外部函数在 main() 上调用时返回分段错误 11.(C++)
- 使用std::tie进行类似golang的错误处理,同时返回结果,是否有缺点?(C++11)
- 是否可以通过使用移动/交换 c++11 来延长返回的临时变量的生命周期
- C++ 14 与 11 - 大小返回不同的值?
- 当加入 C++11 函数的线程仍未终止时,是否可以返回?
- 在 C++11 中创建并返回包含 lambda 成员变量的类
- 使 c++11 Dijkstra 实现返回最短路径
- 具有尾随返回类型的通用 lambda,具体取决于 C++11 中的可变参数
- 分段故障 11 返回时
- C++11 decltype 返回正确的类型,但代码无法编译
- av_buffersink_get_frame() 返回错误 AVERROR(EAGAIN) -11.
- 返回 C++11 中已删除函数的类型
- 从 lambda 内部返回 C++11 中的 lambda 类型(平面映射函数)
- 堆栈弹出操作是否可以安全地返回 C++11 中的值
- 函数返回C++11中的函数指针