简体   繁体   中英

returning a const char* from a function

I have to replace some char array code. So say I have a class that has an std::string member variable.

class foo
{
private:
  std::string _sBar;

public:
  const char* getBar() const { return _sBar.c_str(); }
};

existing code expects that const char* 's are returned in the string accessor functions, so I can't return a const std::string reference.

But isn't there some rule that when the stack unwinds that you can no longer trust the return value from the _sBar.c_str() ?

Yes, that's correct. Better if you ask the caller to supply a buffer with a fixed size say, the caller allocates as:

const int MAX = 1000; // choose some suitable value
char buff[MAX];

And the caller has a foo object,

foo a;

...

a.getBar(buff, MAX);

...

And you define getBar as:

 void getBar(char *buffer, int size) const { 
   strncpy(buffer, _sBar.c_str(), size -1);
   buffer[size -1] = 0;
 }

you can make a copy of that string with new [ ] operator inside your member function, and it will be stored independently from the class object. In the class:

plublic:
const char* getBar() const {
char * str = new char[_sBar.length()+1];
strcpy(str, _sBar.c_str());
return str;}

In main:

foo object;
///some code
const char* bar = object.getBar();
///some code
delete [] bar;

Note it's good style to free the memory using delete [ ].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM