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.