为什么函数返回空对象

Why function return empty object?

本文关键字:对象 返回 函数 为什么      更新时间:2023-10-16

这是c++11。使用两个堆栈的堆栈的简单排序功能。在 sort(( 函数中调试 tempStack 正确填充但 sort(( 函数返回空对象时?

我试图添加std::

move((或std::forward((,但这是不正确的。一般的sort((算法是正确的!此代码编译成功。c++11的一些错误(移动语义(!

我的想法(无法正常工作!return forward>(tempStack(;返回移动(临时堆栈(;

代码(排序(((:

template<typename T>
Stack<T> sort(Stack<T> &input)
{
    if(input.isEmpty()) return Stack<T>();
    Stack<T> tempStack;
    while(!input.isEmpty())
    {
        T element = input.pop();
        while(!tempStack.isEmpty() && tempStack.peek() > element) input.push(tempStack.pop());
        tempStack.push(move(element));
    }
    return tempStack;
}

代码(堆栈类(:

template <typename T>
class Stack
{
public:
    Stack() : top(nullptr), stackSize(0)
    {}
    Stack(Stack &&other) : top(std::move(other.top)), stackSize(std::move(other.stackSize)) {}
    ~Stack() { while (!isEmpty()) pop(); }
    void push(T &&value)
    {
        auto n = new Node(std::forward<T>(value), top);
        top = n;
        ++stackSize;
    }
    T &peek()
    {
        if (!top) throw StackIsEmptyException();
        return top->value;
    }
    T pop()
    {
        if (!top) throw StackIsEmptyException();
        auto value(std::move(top->value));
        auto n = top;
        top = n->next;
        delete n;
        --stackSize;
        return value;
    }
    bool isEmpty() const { return !top; }
    size_t size() const { return stackSize; }
    class StackIsEmptyException
    {};
private:
    struct Node
    {
        Node(T &&v, Node *n): value(std::move(v)), next(n)
        {}
        Node(const T &v, Node *n): value(v), next(n)
        {}
        T value;
        Node *next;
    };
    Node *top;
    size_t stackSize;
};

代码(main(((:

Stack<int> s;
s.push(34);;
s.push(3);
s.push(31);
s.push(98);
s.push(92);
s.push(23);
cout << sort(s).peek() << endl;

当这条线运行时会发生什么?

return tempStack;
  1. tempStack移动到临时对象。
  2. tempStack被摧毁。
  3. 返回临时对象。

在步骤 1 中,tempStacktopstackSize复制到临时对象(这就是移动构造函数的作用(。在步骤 2 中,堆栈中的所有项目都已解除分配。在步骤 3 中,此返回对象的top现在指向已释放的内存。

移动构造函数应将移自对象的top设置为 NULL(可能也stackSize设置为 0(,以便该对象在销毁时不会释放任何内容。

通知移动的对象不应销毁其资源非常重要。例如,您可以使用防护装置防止在对象移动时清理堆栈。

喜欢:

Stack(Stack &&other) : top(std::move(other.top)), stackSize(std::move(other.stackSize)) { other.moved = true; }
~Stack() { if (!moved) while (!isEmpty()) pop(); }