2012-02-27 85 views
1

我想知道C++如何處理由類方法或函數內的指針創建的「對象」的內存。 對於類實施例類內部的指針方法/函數

void Example::methodExample() 
{ 

    ExampleObject *pointer = new ExampleObject("image.jpg"); 

} 

的示例方法我應該以某種方式刪除,或者它自動刪除? 很抱歉,如果我的問題是愚蠢的,但我是初學者:P

回答

2

您有兩個選項

如果你使用原始指針,如您使用的是你的榜樣,您必須是用new創建手動delete對象。

如果你不這樣做,你已經創建了內存泄漏。

void Example::methodExample() 
{ 
    ExampleObject *pointer = new ExampleObject("image.jpg"); 

    // Stuff 

    delete pointer; 
} 

或者你可以使用智能指針,如boost::scoped_ptr或C++ 11的std::unique_ptr

這些對象在被刪除時會自動刪除它們指向的內容。

有些人(像我)會說這種方法是首選,因爲即使拋出異常並且未達到函數末尾,您的ExampleObject也將被正確刪除。

void Example::methodExample() 
{ 
    boost::scoped_ptr<ExampleObject> pointer(new ExampleObject("image.jpg")); 

    // Stuff 

} 
+2

所以我可以完全忘記原始指針,並開始使用增強智能指針? – fex 2012-02-27 20:33:58

+0

**我的意見**是,你可以選擇使用智能指針,只要你可以,只有當你必須使用原始指針。根據你在做什麼,你可能永遠不需要使用原始指針。 – 2012-02-27 21:29:40

+0

@fex:你應該忘記原始指針。除非你在C++庫上工作,否則你永遠不需要它們。 – 2012-02-27 22:12:24

0

我應該以某種方式刪除,或者它自動刪除?很抱歉,如果 我的問題是愚蠢的,但我是初學者:P

是的,你確實需要手動刪除是如下:

delete pointer; 

否則,你將有內存泄漏。


在另一方面,如果聲明是這樣的,那麼它會自動當它超出範圍釋放:

ExampleObject object = ExampleObject("image.jpg"); 
+0

爲什麼downvote? – Mysticial 2012-02-27 19:34:57

0

你應該

delete pointer; 

當你沒有更需要它。指針在函數結束時超出範圍,但內存仍分配在堆上。

1

在現代C++中,你不應該做自己的內存管理。使用unique_ptrscoped_ptr,當指針超出範圍時它將自動刪除指針。

1

如果你的對象被作用在函數中,那麼你的正確的構造就是不使用指針,而是使用自動對象,它應該像這樣創建。

ExampleObject example("image.jpg"); 

你可能在當時,那裏的else條件不會構造對象使用指針在什麼地方,例如,在if結構,然後你以後要使用的對象。

在這種情況下,使用自動指針對象,最好是unique_ptr(如果可用),如果不可用,則使用boost::scoped_ptr,但即使是不贊成的std :: auto_ptr也比原始指針更好。例如:

std::unique_ptr<ExampleObject> example; 
if(usingAnExample) 
{ 
    example.reset(new ExampleObject("image.jpg")); 
} 
else 
{ 
    // do stuff 
} 
// I still need example here if it was created 
1

我認爲與原始指針處理(如你的例子)的appriate方法是店指針作爲類的成員。然後你可以用你想要的任何方法爲這個指針分配內存,然後在的類的析構函數中釋放內存給。沿着這些線:

class Example 
{ 
public: 
    Example(); 
    ~Example(); 

    void methodExample(); 

private: 
    ExampleObject* pointer; 
}; 

void Example::Example() 
: pointer(NULL) 
{ 
} 

void Example::~Example() 
{ 
    if (pointer) // release memory only if it was allocated 
    delete pointer; 
} 


void Example::methodExample() 
{ 
    pointer = new ExampleObject("image.jpg"); 
    // add a safety check to verify if the allocation was successful 
} 
+0

如果這真的是OP想要的,那麼(a)在構造函數中將'pointer'初始化爲null; (b)修正'methodExample'分配給成員; (c)根據[Rule of Three](http://stackoverflow.com/questions/4172722)添加一個非默認拷貝構造函數和拷貝賦值操作符。但我強烈懷疑OP只是想要一個自動對象,而沒有'new'。 – 2012-02-27 17:48:11

+0

謝謝@MikeSeymour!我會仔細閱讀三法則。 – karlphillip 2012-02-27 18:48:53