linux gcc 堆栈,linux gcc 堆栈

new应避免将C ++数组与(即使用动态数组)一起使用。有一个问题,您必须跟踪大小,并且需要手动删除它们,并进行各种整理。

不建议在堆栈上使用数组,因为您没有进行范围检查,并且将数组传递给周围将丢失任何有关其大小的信息(数组到指针转换)。boost::array在这种情况下,应使用将C ++数组包装在一个小类中,并提供一个size函数和迭代器对其进行迭代的情况。

现在,将std :: vector与本机C ++数组(从互联网上获取):

// Comparison of assembly code generated for basic indexing, dereferencing, // and increment operations on vectors and arrays/pointers.

// Assembly code was generated by gcc 4.1.0 invoked with g++ -O3 -S on a // x86_64-suse-linux machine.

#include

struct S { int padding;

std::vector

v; int * p; std::vector

::iterator i; };

int pointer_index (S & s) { return s.p[3]; } // movq 32(%rdi), %rax // movl 12(%rax), %eax // ret

int vector_index (S & s) { return s.v[3]; } // movq 8(%rdi), %rax // movl 12(%rax), %eax // ret

// Conclusion: Indexing a vector is the same damn thing as indexing a pointer.

int pointer_deref (S & s) { return *s.p; } // movq 32(%rdi), %rax // movl (%rax), %eax // ret

int iterator_deref (S & s) { return *s.i; } // movq 40(%rdi), %rax // movl (%rax), %eax // ret

// Conclusion: Dereferencing a vector iterator is the same damn thing // as dereferencing a pointer.

void pointer_increment (S & s) { ++s.p; } // addq $4, 32(%rdi) // ret

void iterator_increment (S & s) { ++s.i; } // addq $4, 40(%rdi) // ret

// Conclusion: Incrementing a vector iterator is the same damn thing as // incrementing a pointer. 注意:如果使用分配数组new并分配非类对象(例如plain int)或不使用用户定义的构造函数的类,并且您不想初始初始化元素,则使用new-allocated数组可能会带来性能优势,因为std::vector将所有元素初始化为构造上的默认值(例如,对于int来说是0) 问题来源于stack overflow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值