I try to avoid having pointers, and instead of doing
std::list<std::pair<int,int>* > myList;
void addElement(int a, int b) {
myList.push_back(new std::pair<int,int>(a,b));
}
I figured i could do something like
std::list<std::pair<int,int> > myList;
void addElement(int a, int b) {
std::pair<int,int> p(a,b);
myList.push_back(p);
}
If i understand the behaviour correctly, this should store a copy of the pair, and automatically delete it when doing myList.clear()
(as opposed to the pointers).
Is this the best way to do it?
Can i expect the compiler to optimize away the unnecessary object p
?
"Can i expect the compiler to optimize away the unnecessary object p?"
Maybe, maybe not. Try this though:
myList.push_back(std::make_pair(a,b));
You usually have better chances of optimization when you work with r-values where applicable.
But even if it's not optimized away, that is no reason to resort to using pointers, especially for such small objects(not that I would advocate using pointers for large objects). Only use pointers when they are semantically the correct thing to use, and that is rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With