The issue I was having in my code involved objects being duplicated (copied) as I stored them in a std::vector. Oh, by the way, I code almost entirely in C++. Anyways, the way this bit of code worked was that a line was read from file, and that line was then used to construct an object of my type. From there, those objects were added to the vector. The problem was, those original objects stuck around, so I'd have TWICE as many objects in existence than I was actually using! I asked for some assistance on IRC and I must say, my life has never been the same.
The "Trick"
Maybe I've just been living under a rock, but I had never seen this before. Apparently, you can arbitrarily create scopes anywhere in your code! I'll demonstrate it below with a basic example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
{ | |
public: | |
Foo() { std::cout << "ctor\n"; } | |
~Foo() { std::cout << "dtor\n"; } | |
}; | |
int main() | |
{ | |
std::vector<Foo> foos; | |
{ | |
Foo foo; | |
foos.push_back(foo); | |
} | |
std::cout << "Only 1 Foo object exists at this point, good!\n"; | |
return 0; | |
} |
Output
$ ./scope
ctor
dtor
Only 1 Foo object exists at this point, good!
dtor
Now, instead of having 2 copies of foo in existence (the one I create, and the one that gets copied into foos), I only have the one inside of foos. Depending on your situation, this is preferable because if you need to add an object to a vector, chances are good that you'll be referencing it from within the vector for the rest of the program.
Hopefully you learned something from this, stay tuned, I'll soon be posting a very amusing and interesting story about my recent job as a contract software developer. Take care.
3 comments:
Fantastic example, I see how that was very helpful.
It is very useful. The only problem with the example you gave is that, if as you say, it is creating two copies of each element then going out of scope does not actually release that resource. C++ does not have a garbage collector as other languages like Java do and therefor you must manage memory yourself. Typically you would use a destructor in C++ to do this.
The object's destructor is called automatically when the object goes out of scope. This is different from the concept of garbage collection in which the collector is aware of when no more references or handles to a resource exist, thus it can no longer be used. In the case of scope, the resource is not visible any more, thus it cannot be used. This obviously isn't the case for dynamically allocated objects because they are in scope for the duration of the program's execution after they have been declared.
Post a Comment