0

C++:可以提前销毁对象,使其存储内存被后续对象重用吗?

在一段 C++ 代码中,在前半部分,使用了对象 a、b;在第二半部分,对象 c、d 被创建和使用。

由于对象 a、b 占用大量内存,我想在第一半部分完成时手动销毁对象 a、b。

我知道我可以使用 new,delete 来实现它。

但是如果我不使用 new 并且仍然想更早地销毁对象(也就是说,在其范围结束之前),我可以手动调用它的析构函数来销毁它吗?这样那部分内存就可以被对象 c 和 d 重用。(我不需要释放内存,因为重用很好。

这是一个伪代码:

monsterClass a, b;
dragonClass c, d;
int i,j,k,l;

a = monsterClass(1000, 2000);
b = monsterClass(2000, 3000);
i = processMethod1(a, b);
j = ...;
k = ...;
l = ...;


// here, I want to destroy a, b, since they are not used any more, while occupy memory.
// The above half part and the below half part use many common variables. 
// So it seems scope {} method makes it inconvenient, 
// since I don't want to create a function with too many parameters.
// I don't want to use new or delete here. I hope it looks simple and not prone to error
// So can I use: ~a, ~b here?

c = dragonClass(400, 3000);
d = dragonClass(500, 4000);
processMethod2(c, d, i);
j = ...;
k = ...;
l = ...;

[更新 1] 所以大多数人建议使用范围,这是一个好方法。我还是很好奇,我可以在那里使用 ~a 和 ~b 吗?我认为这似乎也是一种可行且方便的方式。

[更新 2] 我想出了另一种情况。在这种情况下,不同变量的作用域是交织在一起的!就像这样:a 的范围与 b 的范围有重叠,但它们不包括关系。它是部分重叠的关系。在这种情况下,这是否意味着无法使用范围?最后的手段是使用new和delete,对吧?

4

4 回答 4

3

使用placement new 并手动调用析构函数:

{
  char memory[std::max(sizeof(A),sizeof(B))];

  A* pA = new (memory) A();
  // use `pA`
  pA->~A(); // destruct A

  B* pB = new (memory) B();
  // use `pB`
  pB->~B(); // destruct B
} // `memory` goes out of scope

我建议阅读关于 operator new 的优秀资源:http: //en.cppreference.com/w/cpp/language/new

于 2014-12-05T17:06:15.650 回答
2

你可以把它分解成更小的函数:

void part1() {
    monsterClass a, b;
    a = monsterClass(1000, 2000);
    b = monsterClass(2000, 3000);

    processMethod1(a, b);
}

或较大功能内的块

{
    monsterClass a, b;
    // and so on
}
{
    dragonClass c, d;
    // and so on
}

或使用临时工

processMethod1(
    monsterClass(1000, 2000);
    monsterClass(2000, 3000);
);

如果你做的事情太复杂以至于这些都不合适,你可以弄乱一个联合,或者新的安置;细节会很繁琐,具体取决于您的奇怪要求。

于 2014-12-05T17:14:39.670 回答
1

作为您的代码片段,您可以写为

int i,j,k,l;

{
  monsterClass a(1000, 2000);
  monsterClass b(2000, 3000);
  i = processMethod1(a, b);
  j = ...;
  k = ...;
  l = ...;
}

// here, you want to destroy a, b, since they are not used any more, while occupy memory.

dragonClass c(400, 3000);
dragonClass d(500, 4000);
processMethod2(c, d, i);
j = ...;
k = ...;
l = ...;

// you could use the same technique if there are still e, f or so
于 2014-12-05T17:24:30.220 回答
1

您可以使用大括号手动控制堆栈上对象的生命周期。

void foo()
{
    int x = 5;
    int y = 2;

    {          // This introduces a new scope
    int z = 3;
    }          // After this brace, z is now out of scope

    int a = x + y;
}

但请注意,一旦变量超出范围,则不会指定再次使用此内存的时间。仅仅因为我声明了另一个intnamed a,并不意味着它将被分配过去的地址z

于 2014-12-05T17:03:47.517 回答