We help IT Professionals succeed at work.

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

List244
List244 asked
on
Medium Priority
310 Views
Last Modified: 2010-04-01
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.
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2012
Commented:
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 {

public:

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

private:

char* m_arr;

};

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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
efn

Commented:
> ...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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.