tags:

views:

195

answers:

10

Assume I have some C++ method which returns back a pointer to an object. Something in the header file that looks like this:

uint8_t* getData(void);

This guy returns a byte array, but there is nothing that says if this is a dynamic or statically generated piece of data (local to the class or created with new).

Is there a specific naming convention in C++ to distinguish between methods that return memory that is dynamically allocated (and so must be deleted by the requester), vs methods that just return a reference to a statically define piece of data?

What is the preferred way to do this, or does it depend on the situation?

+4  A: 

In C++, you simply do not hand out raw pointers to clients in the first place. One possible solution:

std::vector<uint8_t> getData();
FredOverflow
not that it is not possible, it is just a bad idea (for the reasons mentioned in the question) and there are alternatives
stefaanv
@stefaanv: it's a good idea, read comments to my answer.
ybungalobill
@ybungalobill: I assume you missinterpreted my comment: it's a bad to hand out raw pointers. I upvoted this answer. But I admit that my comment was too short.
stefaanv
Not necessarily a bad idea. If you construct the vector in the return statement, the compiler will normally optimize out the copy constructor.
John Gaughan
A: 

Put it in the documentation.

PiotrLegnica
+1 unless it is obvious, ownership (i.e. who's responsible for cleanup) should always be documented; in this example, it is obviously NOT obvious :-D
franji1
Worst Advice Ever.
Matthieu M.
@Matthieu Yeah, you're right. We shouldn't document our code.
PiotrLegnica
Alf P. Steinbach
@Piotr: the issue is not that documentation is bad, it's that documentation as the sole way to enforce something as important as resource ownership is totally unreliable, especially in a language where you can just ignore the return value of a function...
Matthieu M.
+3  A: 

My conventions are:

uint8_t* getData();

is statically allocated, or at least it's not my responsibility for deleting this data. However if it's an array I would write:

pair<uint8_t*,uint8_t*> getData();

Or define a container for that.

auto_ptr<uint8_t> getData();
unique_ptr<uint8_t> getData();

allocates single object and I own it from now on.

shared_ptr<uint8_t> getData();

allocates single object with shared ownership.

vector<uint8_t> getData();

allocates an array, vector owns the memory.

ybungalobill
larsmans
@larsmans: I write this only if it's really a performance issue, for three reasons: 1) it's an optimization, what I really mean is to *return* a vector 2) compiler can optimize it in many cases through copy elision 3) we are moving towards C++0x with rvalue references, hooray!
ybungalobill
Ah! Better go read the C++0x draft. Thanks!
larsmans
I realize it's the "new cool" to rely on compiler optimizations (seriously, what can go wrong here), but why not just write proper code?
ttvd
RVO is in the '03 standard, is something that every major compiler will do with optimizations enabled, and can be done in most useful situations without even thinking about rvalue references. Output parameters make code more complex and harder to read. "Proper code" should be simple and clear first and foremost. Even if the optimization doesn't apply, the structure of the application will determine whether or not that matters. And if it does matter, code is easy to change.
Steve M
Can anyone explain why -1?
ybungalobill
@Steve: most compilers perform RVO even *without* optimizations enabled
jalf
You can use unique_ptr and shared_ptr with arrays too, see my "regarding arrays" [comment](http://stackoverflow.com/questions/3948645/name-convention-for-deleting-data-in-c/3948667#3948667), and I prefer that to a pair pointing to dynamically allocated memory that doesn't also convey how it should be deallocated.
Roger Pate
@Roger: I don't advocate returning a pair for dynamically allocated memory. Yes you can use even std::shared_ptr with custom deleter. Anyway I prefer shared_ptr to a vector if it's shared ownership and just vector otherwise.
ybungalobill
I just passed out from holding my breath for C++0x. Shouldn't it be called C++1x now, or perhaps even better; C++xx?
Ed Swangren
Thanks for this. Lots of great answers on my first post. I'm actually returning a ptr to a class variable on an object that will always exist while the program is running. I don't want to copy anything I just want to return a pointer back for performance reasons.
Ferretzor
+2  A: 

EDITED !
If you return pointer to a locally allocated array, the program will crash when you try to use this pointer, as after exiting from the function, the array will be destroyed. Actually, a crash will be the best behavior, because this situation is undefined behavior. Here's why - you return a address of something, that is not existing anymore. So, the best think that could happen is a crash (after you try to use it anyhow). The other option is this address to be an address of another object in your program (you don't know which one), so if you try to modify it.. it's really bad thing.
The other variant - returning pointer to array, that's allocated with "new" is very dangerous and it's a potential memory leak. So, use smart pointers - it's the best way (: /* see Roger Pate's comment at this question about usage of smart pointers */
The other way is to return a copy of the array (using std::vector), but it's very slow (if you're array is big, especially when the array is from some big user-defined type), and it's not really good idea in the most cases.

// Thanks to ybungalobill, Steve and Roger Pate for their remarks!

Kiril Kirov
Can somebody tell me what is this -1 for ? I mean, I wanna know my mistake
Kiril Kirov
Although it's not my vote, I guess it's for "if you return pointer to a static allocated array the program will crash".
ybungalobill
I thought about that, but it's true. It's completely possible to create static array and return pointer to it. As I said, the program will crash (or it's undefined behavior ), when you **try to use it**, not when you return it.
Kiril Kirov
Sorry, but it's not. `int* f() { static int a; return } ... f()[0] = 0;` is completely defined.
ybungalobill
We're talking about arrays. int* f() { int a[100]; return a; } is not defined, as *return a* will return address to something, that's not existing, so manipulating the returned address is not defined, I guess. I mean, it could crash, but if the address is in the address space of the program, this could do something really bad. Anyway, thanks for your remark, it's really useful.
Kiril Kirov
Sorry for the dumb question and for the off-topic, but how you edit your post, so that the code to me with gray background? I didn't see this anywhere in the editing tips :/ Thanks in advance.
Kiril Kirov
It doesn't matter for the question if that's an array or not. What you write is **not** a static array. statically allocated array would be `static int a[100]; return a;`. For your formatting question, use 0x60 ascii character to delimit inline code. it's on the tilde ~ key.
ybungalobill
Yes, it's not static array, sorry, my bad. I meant not dynamically created. What's the word for that? Thanks for the ~ !
Kiril Kirov
"Automatic" or "local" storage duration are what people typically use. Automatic is in the standard.
Steve M
Argh, yeah :) Sorry.... :X Thanks Steve.
Kiril Kirov
*Regarding arrays:* By default, auto_ptr and shared_ptr use delete rather than delete[]. There's a shared_array analog to boost::shared_ptr. For 0x's std::unique_ptr, you need `unique_ptr<uint8_t[]>` (note the array type). You must not use auto_ptr with arrays. You must not use 0x's std::shared_ptr with an array unless you specify a deleter that does the right thing (see §20.9.11.2.1p4 in the 0x FCD for example).
Roger Pate
Alf P. Steinbach
A: 

Indeed - it's very rare that you would actually want to return a pointer to non-dynamically allocated memory. I don't believe it will actually cause a program crash - once I wrote a threading library which used array declarations to inflate the run-time stack and store space for threads; the fact that the memory it's pointing to can change at random is what's dangerous.

Sam Dufel
A: 

One cannot return static data pointer or of local variable since as the stack unwinds the object destructs. It has to be dynamically allocated and it's always the callers responsibility to free it since the function doesn't know when to free it.

Also, please keep in mind, many functions need special deallocaters and doing delete or delete[] is not always the right option. You might end up corrupting the heap! Read the function documentation for that info.

Samrat Patil
A: 

If it is the client's responsibility to manage the memory returned, then some form of wrapping class should be used that handles this responsibility. When using an array you should almost always return a std::vector, because this will also manage the array aspects such as the size, resizing, etc, but for a raw pointer you should typically use a std::auto_ptr or std::shared_ptr. If you're writing a module intended to be used between compilers, write your own. It's easy to return a proxy object that can be converted into various brands of smart pointer.

DeadMG
A: 

If the functions return pointers, then use getData for getting access to memory without taking ownership of it and adoptData for access and taking ownership. At least that's the convention I've seen used most often.

But as others have said, return a container, smart pointer or something else that will automatically handle the memory. RAII is your friend.

And don't forget to state in the API docs of both functions if they transfer ownership or not. The convention is great for people who know it, but it still has to be convenient for those who don't.

Lucas
+2  A: 

In Clang there is a simple convention (check it out here):

  • getX returns a pointer, not ownership
  • takeX returns both pointer and ownership

However, as has been noted, I would lift the compiler abilities here and return a smart manager (smart pointer, container, whatever) rather than a naked pointer when returning ownership.

It's way too easier to let a memory leak slip in when all you have to help is a naming convention... you can still keep the naming convention though ;)

Matthieu M.
A: 

As many have said, don't return a raw pointer. If you want the data to be deleted by the requester (for some reason), you can use something like shared_ptr or auto_ptr, in which case the caller cleans up the returned value (weather he wants to or not). If instead you are returning a member of some class that doesn't get cleaned up, then don't return a pointer at all, return a (possibly const) reference.

TokenMacGuy