0
#ifndef UNICODE
#define UNICODE
#endif

#include <iostream>
#include <Windows.h>
#include <queue>

using namespace std;

void addSomeContent(queue<TCHAR*> &s)
{
    static int counter=0;
    TCHAR* buffer = new TCHAR[250]; //Allocate memory on heap

    wsprintf(buffer,TEXT("foo%d"),counter);

    s.push(buffer);
    counter++;

    if(counter < 10)
    addSomeContent(s);

}


int main (void)
{
    queue<TCHAR*> strings; 

    addSomeContent(strings);

    while(!strings.empty()) 
    {   
        wcout<<strings.front()<<endl;
        strings.pop();
    }

    //Here I want to destroy the "buffer" from the function "addSomeContent"
    wcout<<TEXT("Memory has been cleaned!\n");

    system("pause");
    return (0);
}

関数の最後でワイド文字配列を削除した場合、それを参照するキューを処理できませんでした。今、私の単純なプログラムはコンパイルされて正常に動作しますが、明らかにゴミをヒープに保持することは安全なプログラミング手法とは見なされません。
前回使用した直後の「バッファ」を削除するにはどうすればよいですか?

4

3 に答える 3

2

キューにunique_ptrを使用することについて、Sethに同意するか、単に電話することができます

   delete[] strings.front()

の前にstrings.pop()

front()これから実行しようとしている要素、つまり、最新pop()の要素ではなく、キュー内の最も古い要素を確実にクリーンアップするために使用する必要があります。back()

于 2012-09-21T04:55:06.183 に答える
2

を使用しqueue<unique_ptr<TCHAR[]>>て、メモリの割り当て解除を完全に回避するか、メモリを削除する前に単にメモリの割り当てを解除することができますqueue

delete[] strings.front();
strings.pop();
于 2012-09-21T13:17:21.713 に答える
1

文字列だけを操作したい場合は、

typedef std::basic_string<TCHAR> tstring;
std::queue<tstring> strings;

それ以外の場合は使用できます

std::queue<std::unique_ptr<TCHAR[]>> strings; // notice the [], they are important!

unique_ptrはC++11ですが、すべての主要なコンパイラーでサポートされていると思います。これを手動で削除することすら考えません。エラーに対して非常に脆弱であり、例外安全ではありません。

于 2012-09-21T04:57:32.503 に答える