Error with basic string

Ajay Bansal Ajay_Bansal@infosys.com
Thu Jan 23 18:57:00 GMT 2003


This is actually not dead object. Func is a member of a class & "string
a" is also a member of the same class.. :)

This was just a sample program.. 

But anyway. Thanks a lot.. :).. It has worked.. 

-----Original Message-----
From: Rupert Wood [mailto:me@rupey.net] 
Sent: Friday, January 24, 2003 12:02 AM
To: Ajay Bansal
Cc: gcc-help@gcc.gnu.org
Subject: RE: Error with basic string 


Ajay Bansal wrote:

> char *func(string a, int n)
> {
> 	a.resize(n);
> 	return a.begin();
> }

a.begin() is an iterator. You'll have to dereference it to get the
character and then re-reference that for the pointer, i.e. (bracketed
for clarity)

    char *func(string a, int n)
    {
        a.resize(n);
        return &(*(a.begin()));
    }

*However*

    1) you're not passing your string by reference; what you're
       telling it to do is to take a copy of string a, resize the
       copy to n characters and then return a pointer to the first
       character in the copy - i.e. a pointer to memory owned by a
       dead object

    2) (I'm not an STL guru so take this with a pinch of salt)
       I don't think there's a requirement that the string be
       stored continuously in memory, except for a read-only copy
       between c_str() the next non-const operation. It looks like
       you want func to allocate you an n-byte continuous character
       buffer in a basic_string and, whilst some implementations will
       give you this, I don't think you can assume all will. (But you
       probably know this - the comment about changing the return
       type?) I can't tell you if G++'s STL plays along.

Rup.



More information about the Gcc-help mailing list