如何释放堆栈上的变量? [英] How to deallocate variables on the stack?

查看:149
本文介绍了如何释放堆栈上的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法释放在堆栈上创建的变量和/或对象?我特别谈论堆栈而不是堆。

Is there a way to deallocate variables and/or objects created on the stack? I am specifically talking about the stack not the heap.

我不想辩论这是否有用或好的做法,我只需要知道是否可能。

I do not want to debate whether this would be useful or good practise, I just need to know if it's possible.

我知道它超出范围时自动释放。

I know it automatically deallocates when it goes out of scope. I want to deallocate it BEFORE it goes out of scope.

我正在使用C ++。

推荐答案

您不能提前终止自动对象的生命周期,但您可以随时终止动态对象的生命周期。一个动态对象可以在堆栈上创建,就像一个自动变量,但它是一个头发棘手。

You cannot prematurely end the lifetime of an "automatic" object, but you can end the lifetime of a dynamic object at any time. A dynamic object can be created on the stack just like an automatic variable, but it's a hair trickier.

#include <new>
#include <string>
int main() {
    typedef std::aligned_storage<sizeof(std::string)> stringbuffer;
    stringbuffer buff;
    std::string& str =*new(buff)std::string("banana"); //str alive on stack
    std::cout << str;       
    str.~std::string(); // str is destroyed. DO NOT FORGET
    std::cout << '\n';
}

这是容易出错的,所以当然, boost具有此代码

This is error prone, so of course, boost has code for this.

int main() {
    boost::optional<std::string> str;
    str = "banana"; //str is alive on the stack
    std::cout << str;       
    str = boost::none; //str is destroyed.  Ok to forget
    std::cout << '\n';
}

这两个都避免了FredOverflow的回答的潜在UB,因为如果一个异常在对象不活动时抛出,析构函数不会自动在死对象上调用。

Both of these avoid the potential UB of FredOverflow's answer, since if an exception is thrown while the object is not alive, the destructor is not automatically called on the dead object.

Azza注意到这不会释放空间,它只是破坏。不可能提前释放空间。

Azza notes that this does not deallocate the space, it merely destructs. It is impossible to deallocate the space early.

这篇关于如何释放堆栈上的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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