【问题标题】:Freeing the memory when pop from stack of struct从结构堆栈中弹出时释放内存
【发布时间】:2015-08-13 04:38:45
【问题描述】:

我使用了一堆结构体。

struct stack_values {
    long long int sp;
    bool sign; //true=sum, false=sub
    long long int imm;
};
static std::stack<stack_values> sosp;

我用这段代码压栈;

stack_values sosp_values;
sosp_values.sp = 0; 
sosp_values.sign = true;
sosp_values.imm = 0;
sosp.push(sosp_values);

我想知道当我调用sosp.pop(); 时,C++ 是否释放了它在我推送时为sosp_values 分配的内存。

如果没有。如何释放内存。

stack_values top = sosp.top();
sosp.pop();
delete top;

上面的代码不起作用,因为变量top不是指针。

【问题讨论】:

  • 是什么让您认为std::stack 在元素为pop()ed 时不会释放内存?
  • 我有一个巨大的堆栈,里面有意想不到的值。所以我想知道问题是因为内存分配还是其他原因。

标签: c++ memory-management struct stack


【解决方案1】:

当您推送结构时,堆栈会将其复制到其内部内存中,从而创建一个新对象,该对象是方法推送参数的副本。当您调用方法 pop 时,堆栈会调用相应内部对象的析构函数。

这是一个简单的演示程序

#include <iostream>
#include <stack>

struct A
{
    A() { std::cout << "A::A()" << std::endl; }
    A( const A & ) { std::cout << "A::A( const & )" << std::endl; }
    ~A() { std::cout << "A::~A()" << std::endl; }
};

int main()
{
    std::stack<A> st;

    std::cout << "Calling push()" << std::endl;
    for ( size_t i = 0; i < 3; i++ ) st.push( A() );

    std::cout << "\nCalling pop()" << std::endl;
    while ( !st.empty() ) st.pop();
}

程序输出是

Calling push()
A::A()
A::A( const & )
A::~A()
A::A()
A::A( const & )
A::~A()
A::A()
A::A( const & )
A::~A()

Calling pop()
A::~A()
A::~A()
A::~A()

然而,销毁对象并不意味着堆栈释放已分配的内存。它可以为将来可能被压入堆栈的元素保留它。

【讨论】:

  • 非常感谢,这个解释很清楚了。
猜你喜欢
  • 2016-07-25
  • 2018-11-29
  • 1970-01-01
  • 2012-09-17
  • 2014-04-20
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多