Re: char array and delete
In article
<d2dd48fd-47f9-4fb4-8131-c3b63717d5ac@m36g2000hse.googlegroups.com>,
<Free0017@gmail.com> wrote:
when i do
char * text = "foo";
and later in a if condition i can assign it to another one that was
allocated with new
how do i know if i can call delete[] on text ?
if i delete[] text when text was assigned as char * text = "foo"; i
get an error.
with just char * text, you can't.
with some class it is possible. My choice would be shared_ptr<char>
with one of two deleters but that is only because I don't know more
about how text is used.
struct no_deleter
{
void operator (void *){}
};
struct array_deleter
{
void operator ()( char *p) {delete [] p;}
};
inline char * create_on_stack(char *p)
{
return shared_ptr<char>(p,no_deleter());
}
inline char * create_on_heap(int n)
{
return shared_ptr<char>(new char[n],array_deleter());
}
and use the appropriate of the free functions above to get a
shared_ptr<char>. then
shared_ptr<char> text = create_on_stack("Hello World");
// ...
text = create_on_heap(100);
would delete [] text when appropriate.
There would be no operator [] for text, but anytime you want to
manipulate the text string text.get() would return a char * just don't
delete it and so if text is a local variable of main()
void do_something(shared_ptr<char> &p)
{
if(condition)
{
p = create_on_heap(1000);
fill_data(p.get(),1000);
}
}
int main()
{
shared_ptr<char> text = create_on_stack("Hello World")
do_something(text);
}
would delete [] or not delete at all depending on whether the ptr was
move to the heap or not.
This is not the only solution, but probably easiest to use...
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]