Tom*_*ica 2 c++ pointers iterator
我有一些问题转换std::list<MyType>::iterator
为MyType*
.我有一个数组,MyType
当我循环它时,我打电话给一些void doSomething(const MyType* thing)
.最后我这样做:
std::list<MyType> types = ... something here ...;
for( std::list<MyType>::const_iterator it = types.begin(), end = types.end(); it != end; ++it ) {
doSomething(&*it);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,无论我是否MyType
通过此操作创建了内存副本:
&*it
Run Code Online (Sandbox Code Playgroud)
试图简单地传递迭代器就像它是指针一样,或者将迭代器强制转换为指针引发的编译器错误.
不,序列*
和&
不创建副本:
*
应用于迭代器会产生一个引用&
应用于引用会生成原始地址无论这两个步骤需要复制MyType
的数据.
注意:如果存在重载运算符&
,则使用std::address_of(*it)
表达式会更安全.