为什么函数返回空对象
Why function return empty object?
这是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;
-
tempStack
移动到临时对象。 -
tempStack
被摧毁。 - 返回临时对象。
在步骤 1 中,tempStack
的top
和stackSize
复制到临时对象(这就是移动构造函数的作用(。在步骤 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(); }
相关文章:
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?
- 从我的对象返回静态数组
- 将unique_ptr作为<Object>unique_ptr<常量对象返回>
- 从右值对象返回成员
- 视觉对象 返回 C++ 中的双精度值
- 为什么类型为 sf::Text 的对象返回不同的 getPosition().y 和 getLocalBounds().
- std::min_element 从类对象返回意外结果
- C++无效的对象返回语义
- const引用是否延长临时对象返回的临时对象的寿命
- 将 NULL 作为对象返回时未收到任何警告
- 如何在 C# 中从 com 对象返回数组(double[])
- 从重载运算符返回引用,并使用临时对象返回表达式
- Cin 对象返回值 c++
- 将变量作为类对象返回
- 使用可更改对象返回只读的最佳方法是什么
- 如何在Cython中从另一个包装对象返回包装的c++对象
- 当对象返回时,c++动态数组被清除
- 从带有动态字段的函数、对象返回
- 从堆栈上的匿名对象返回对*this的引用