best way to do handle return variables

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

best way to do handle return variables

Postby tamer » Wed Jul 07, 2010 8:17 am

Hi, I am still learning C++
I am confused regarding the best way to handle a return variables from a method.
I have a class with one method that return a char* var
this var was created using the new keyword
this var was declared as a global variable in order to be deleted later on on the destructor method.
Code: Select all
char * myfunc()
{
var= new char[len];
return var;
}


I know that I must call delete[] var in order to free memory correctly.
But where exactly should I do this?
at the destructor of the class ?
is what I am doing is correct?
Then how should I handle the return value correctly if i want to keep using it after the object is destroyed?

thanks.
tamer
 
Posts: 1
Joined: Wed Jul 07, 2010 8:09 am

Re: best way to do handle return variables

Postby Alvaro » Wed Jul 07, 2010 11:54 am

You don't have to make var global to be able to delete[] it later. Your function is returning the address that delete[] needs.

The correct way to handle this is to return a type that will take care of handling the memory automatically. In this case, std::string or perhaps std::vector<char>, depending on what you intend to do with this variable.
User avatar
Alvaro
Moderator
 
Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

Re: best way to do handle return variables

Postby Sunny » Thu Jul 22, 2010 5:25 pm

you can also use std::shared_ptr with a little hack:

Code: Select all
template<typename T>
class arrayDeleter { // hack
public:
    void operator() (T* ptr) {
        delete[] ptr;
    }
};

std::shared_ptr<char> function() { // your function
    return std::shared_ptr<char>(new[len], arrayDeleter<char>());
}


or you just use boost::shared_array:


Code: Select all

boost::shared_array<char> function() {
    return boost::shared_array<char>(new[len]);
}
User avatar
Sunny
 
Posts: 6
Joined: Thu Jul 22, 2010 5:01 pm

Re: best way to do handle return variables

Postby RubyRails » Mon Sep 13, 2010 2:25 am

Thanks for this. I am also having a problem with return variables in C. It really helped my problem a lot. By the way I am making a research paper about C++ and I read several custom essays about it.
RubyRails
 
Posts: 4
Joined: Mon Sep 13, 2010 2:22 am

Re: best way to do handle return variables

Postby Jiellen_27 » Wed Oct 27, 2010 9:25 pm

Sounds very interesting. I'm wondering how this relates to remote stuff you can do with Media Mover. Isn't there something similar already? That might be a conceptually better place for it in the stack of modules, but I'm not sure.
Jiellen_27
 
Posts: 5
Joined: Wed Oct 27, 2010 8:53 pm


Return to For Beginners

Who is online

Users browsing this forum: No registered users and 0 guests