0

Lets consider the following code:

void main(int argc, char* argv[])
{
Foo foo;
//at this point I don't need foo any more
//a lot of stuff here
}

If I only need foo only for short amount of time,isn't it would be better to allocate it on a heap and delete before executing rest of the code?

4

1 回答 1

11

不,最好写一个内部范围

int main()
{
    {
        Foo foo;
        // use foo
    }
    // more code
}

但是这样做应该暗示将 foo 放在一个完全独立的函数中可能会更好。

不过,这里没有理由使用堆分配。该解决方案将比问题更糟糕。

于 2013-04-19T09:26:19.407 回答