当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Avoiding pointers in std::list

问题描述:

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.

网友答案:

In C++0x, you could use std::list::emplace_back, which uses perfect forwarding to pass arguments to the object constructor, thus creating the std::pair in-place. But otherwise no; it'll need to create a temporary.

网友答案:

It is unreasonnable to expect the copy to be optimized out. It might be, but it is somewhat doubtful.

The main issue is that an argument of a function must be fully evaluated before the function is called, so while for the case of a pair of ints, it might indeed work (it can be inlined, so the compiler may see there is no exception/side effet), it is in general plain unreasonnable.

On the other hand, given the high cost of a dynamic memory allocation, the copy is bound to be cheaper in this particular case anyway!

分享给朋友:
您可能感兴趣的文章:
随机阅读: