Question

I would like to use the following static function. This function will in turn compute the input, and std::cout a result. After the static function is called and taken off of the stack, will all of this memory associated with this class be freed? Is this equivalent to making an instance of this class within the scope of main, or would it only exist for the duration of this function call? Assume that the function is called as it is below in the main function. Also, further reading links would be great.

typedef std::vector< std::vector<int> > matrix;    
    class LCS
        {
            public:
                static void getLCS(std::string,std::string);
            private:
                void compute_alignment();
                std::vector<std::string> f1,f2;
                matrix cost,link;
        };
int main(int argc, char* argv[])
{
    //check command line args
    if(argc != 3){std::cout<<"usage: ./exe file1.txt file2.txt";exit(1);}
    //compute
    LCS::getLCS(argv[1],argv[2]);
}
Was it helpful?

Solution

Judging strictly from your question, all of the variables declared inside of getLCS will die after the function is done if they are declared on the stack (no naked new of any kind). Nothing else should live beyond that. Calling the static function also does not create a new LCS class: static functions on classes behave almost exactly like free-functions, except they can have access modifiers placed on them for scoping within the class. Static data and methods operate independently of their classes unless you explicitly use and intermingle them in member functions.

EDIT:

Note that this is true of ALL C++ functions. Objects and primitives that are made on the stack will die/go-out-of-scope when that function / scope dies. As bonus fun, you can even create scope by slapping some braces { /* ... */ } around some code arbitrarily! But it's usually not necessary to do stuff like that.

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top