Я проиллюстрировал проблему с комментариями в приведенном ниже коде:
class MyClass //Some string-like class that encapsulates a dynamic char array.
{
public:
MyClass(unsigned int size)
{
data = new char[size];
}
char* GetCharArray() //In places where passing the raw array is needed, I call this method, but I want to create a separate char array and not touch the original one.
{
char* temporary = new char[size + someNumber];
for(int i = 0; i < size; i++)
{
temporary[i] = data[i];
}
DoSomeOperationForRemainingCharacters(temporary);
return(temporary);
}
private:
char* data;
unsigned int size;
};
void SomeFunc(char* c);
int main()
{
MyClass string(50):
SomeFunc(string.GetCharArray()); //A new char array is allocated here, but it is
// never deleted. If I return a templated pointer wrapper that wraps the array
// and deletes it in the destructor, the wrapper dies at the end of
// GetCharArray(), so by the time it passed to SomeFunc(), the char array is
// already deleted. What else can I do?
}
Может быть, мне нужно создать небольшую систему сбора мини-мусора?
Почему вы возвращаете char *? вы можете вернуть std::string
вместо этого, которая будет управлять собственной памятью.
Или при использовании массивов других типов std::vector
будет управлять хранилищем для вас
Вы, где скрываете комментарий в своем коде, который может объяснить источник вашего замешательства - //A new char array is allocated here, but it is never deleted. If я return a templated pointer wrapper that wraps the array and deletes it in the destructor, the wrapper dies at the end of GetCharArray(), so by the time it passed to SomeFunc(), the char array is already deleted. What else can я do?
//A new char array is allocated here, but it is never deleted. If я return a templated pointer wrapper that wraps the array and deletes it in the destructor, the wrapper dies at the end of GetCharArray(), so by the time it passed to SomeFunc(), the char array is already deleted. What else can я do?
Ваше выражение неверно. Временное умрет после оценки всего выражения. Предположим, что эти функции существуют:
void SomeFunc(const char* input); //old style C function that expects a raw char pointer
//creates a temporary string and returns it
std:string GetString() {
std::string temp = "whatever";
... lots of manipulation ...
return temp;
}
И вы оцениваете это выражение:
SomeFunc(GetString().c_str());
Стандарт C++ гарантирует, что временная строка, возвращаемая GetString(), будет освобождена только после вычисления всего выражения. с C++ 11 move-ctor временной массив символов внутри std::string
не будет скопирован без необходимости
Используйте std::string
для возврата char
-based строки.
Он обрабатывает выделение памяти и освобождение для вас.
std::vector
(илиstd::string
), а не просто для его использования? Если это так, вы должны использовать RAII, чтобы заново его изобрести - это обычная «система мини-сбора мусора» в C ++.