簡體   English   中英

如何釋放“ new”分配的內存,但不顯式引用相應的指針

[英]How to free up memory allocated by “new”, but without referencing corresponding pointer explicitly

我的應用程序有2個狀態,例如foo和bar。 每個狀態都有一些對象,但是由於它們在內存方面很大,因此我想在進入狀態時使用新對象創建它們,然后在需要更改狀態時釋放分配的內存。 我有一個對應於每個狀態的函數,該函數返回void *。 這將代表在每種狀態下相關的對象的地址。

所以一般的想法是

void* vPtr;
if (state == foo) { vPtr = foo(); }
else if (state == bar) { vPtr = bar(); }

//then, using the knowledge that all the object(s)
//are located at vPtr, do things with those objects

簡而言之,這就是foo的樣子

void* foo()
{
    //if first time executing foo, create some new object(s) and return a pointer 
    //to them
    if (firstEntry)
    {
        firstEntry = false; 
        Thing *thingPtr = new Thing; //create new Thing
        return (void*)thingPtr;      //return pointer to objects so they
                                     //can be used elsewhere in the application
    }

    else 
    {
        //do some things
        //..

        if (timeToLeaveStateFoo)
        {
            //  how to free up memory at location "thingPtr" ??
            //  can't use delete(thingPtr)

            return bar();  //where bar is defined similarly     
        }

        else {return vPtr;}
    }
}

如果這不是一個具體的示例,我深表歉意,我試圖將問題歸結為相關的內容。 我想最重要的是,有一種方法可以釋放“新”分配的內存,而無需顯式引用“新”返回的指針。 我知道地址,這還不夠嗎?

調用delete時,您不會顯式引用原始指針。 您只需傳遞new最初返回的值的副本。

由於您的程序始終僅處於兩個狀態中的一個,而兩個狀態都有一些大對象,因此您可以考慮使用匿名結構的聯合,其中包含每個狀態的必要對象並放置新的/刪除的位置。 盡管如此,那可能是嚴重的過早優化。

我不明白為什么您不能使用簡單的類層次結構和虛擬方法解決此問題:

class A {
  virtual void foo() = 0;
  virtual ~A();
};

class Foo : public A {
  virtual void doStuff() { /* do "foo" stuff here ... */ }
};

class Bar : public A {
  virtual void doStuff() { /* do "bar" stuff here ... */ }
};

A *a_factory(bool first_time) {
  if (first_time) { return new Foo(); }
  else { return new Bar(); }
}

void baz(A *&thing) {
  a->foo(); // do regular foo stuff ...

  if (some_test) {
    delete a;
    a = a_factory(false);
    // ...
  }
}

是什么阻止您按照這些思路來做事?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM