What is the best way to return a class' private character array?

If a class has a private array member, what is the best way to return this?
Currently, I have it returning as const char* so that they may not alter it,
however this requires them to have a const array themselves, and I don't
know that I like that.

I also have tried a static variable as the return instead, however with this I
don't know that I like the memory being held until my application ends.

Then, I know I could return a string, or use new/delete... But at this point
I figured I would just come and get some input on what all of you feel is the
best way to go about doing such a thing.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Do you want the array to be modifyable by the callers or do you want to keep the original contents? There are several scenarios, assuming the latter I'd probably pick a std::string to handle that transparently if you wnt the original data in your class to be unchanged, e.g.

#include <string>
using std::string;

class foo {


string get_string () const { return string(m_arr);}


char* m_arr;


Thus would allow the caller to fiddle with the data that is returned without changing your original.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
> ...this requires them to have a const array themselves

Why?  For read access, a client can use the pointer to const char, and to change the string, the client would have to copy it to a non-const array.

For the greatest efficiency, return a pointer to const char.  For the greatest simplicity, convenience, and safety, return a string, as jkr suggested.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.