vector保存局部变量和指向局部变量的指针区别

一、结论

vector保存局部变量:可以,因为在vector上创建对象也是在堆上;

vector保存指向局部变量的指针:不可以,因为局部变量离开作用域后,就会释放,指向局部变量的指针会指向未知的地址空间,指向的内容未知。

demo1:验证vector即使局部变量也是堆上上分配。

结果:返回的vector中保存的局部变量地址没有变化。

#include <iostream>
#include <vector>
using namespace std;

// 返回一个vector变量,并打印vec的地址和存放在容器中第一个数据的首地址
vector<int> fun() {
    vector<int> vec;    // 创建vector
    vec.push_back(10);   // 添加一个元素

    cout << "fun():&vec" << &vec << endl;
    cout << "fun():&vec[0]" << &vec[0] << endl;

    return vec;   // 返回vector

}

int main() {
    vector<int> vec;   // 创建一个vector
    vec = fun();      // 接收传来的参数

    cout << "----------------------" <<endl;

    cout << "main():&vec" << &vec << endl;
    cout << "main():&vec[0]" << &vec[0] << endl;
    return 0;
}

Ref:https://xie.infoq.cn/article/bc30c36a64ed67985cf7c8da1

二、拓展

vector是在堆上分配对象,那么怎么释放堆上的空间,避免内存泄露?
Answer:提供有两个方法,clear()、swap(),可以看看官网说明。
clear是清空vector,size变0,capacity不变
swap是size变0,capacity变0

void clear() noexcept;
Clear content
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.

A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:
 
vector<T>().swap(x);   // clear x reallocating 

demo2:验证clear和swap方法

#include <iostream>
#include <vector>
using namespace std;
void func()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);

    cout << "size:" << v.size() << endl;
    cout << "capacity:" << v.capacity() << endl;

    v.clear();
    cout << "after clear size:" << v.size() << endl;
    cout << "after clear capacity:" << v.capacity() << endl;

    vector<int>().swap(v);
    cout << "after swap size:" << v.size() << endl;
    cout << "after swap capacity:" << v.capacity() << endl;
}

int main() {
    func();
    return 0;
}

最后:问题来了,STL为什么这么设计?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值