Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding pointers in std::list

Tags:

c++

list

std

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?

like image 932
Mikael Öhman Avatar asked Dec 10 '22 06:12

Mikael Öhman


1 Answers

"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.

like image 76
Benjamin Lindley Avatar answered Dec 31 '22 23:12

Benjamin Lindley