0

I am building a simple package manager for my new Linux distro (check it out as soon as I finish) and have run into a problem. My install() and remove() functions need to access an unspecified amount of Package objects. This is the install function.

void install(int argc, char *argv[]) throw()
{
        for (int i = 2; i <= argc; i++)
        {
                Package p(argv[i]);
                p.fetch();
                cout << "Package " << p.getRef() << " retrieved succesfully from server.\n";
                p.install();
                cout << "Package " << p.getRef() << " installed succesfully.\n";
        }
}

I suspect this code isn't entirely kosher; this would result in several objects named p which would probably cause a compilation and/or runtime error. What I'm looking for is either a way to change the name p in each iteration of the loop or delete p after one iteration so I will be free to create another object of that name.

2
  • 4
    You need to go read a good book on C++, especially about scoping rules. The variable p is declared locally inside the loop, every time the loop iterates a new and unique object is created. Commented Dec 31, 2014 at 1:15
  • 1
    Good Books: stackoverflow.com/questions/388242/… Commented Dec 31, 2014 at 1:19

1 Answer 1

1

There is no discernible problem with your code nor will there be any issue with multiple objects. The variable p has automatic storage duration and is destroyed when it goes out of scope. When this means is that at the end of each iteration of the for loop p is destroyed and no longer exists.

Sign up to request clarification or add additional context in comments.

2 Comments

I thought the object just stayed in existence throughout the loop. I didn't realize that the content was destroyed in each iteration.
No. Because it has automatic storage duration its lifetime is limited to the scope it is defined in. In this case the lifetime of p is defined by the compound statement following the for statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.