zoukankan      html  css  js  c++  java
  • c++ 的 auto 好像不是那么智能

    class MyCircularDeque {
    public:
        std::vector<int> q;
        const vector<int> & getV() const {
            return q;
        }
    }
    
    int main() {
        MyCircularDeque mcd(10);   
        const std::vector<int> & vc = mcd.getV();
        // 这里 vc0 被 auto解析为 vector<int>类型, 类似默认拷贝构造一个新的栈变量
        auto vc0 = mcd.getV();
        mcd.insertFront(0);
        mcd.insertLast(9);
    
    
        std::cout << "%u vc0 :"<<&vc0<<std::endl; // 0x7ffe2ba60260
        std::cout << "%u vc :"<<&vc<<std::endl; // 0x7ffe2ba60288
        std::cout << "%u mcd :"<<&mcd.q<<std::endl; // 0x7ffe2ba60288
        std::cout << "%u getV :"<<&mcd.getV()<<std::endl; // 0x7ffe2ba60288
    }
    为什么会这样那,我们深入源码看一下
     
    740  operator=(const vector& __x)
    // ...
    std::__alloc_on_copy(_M_get_Bit_allocator(),
                         __x._M_get_Bit_allocator());
            _M_initialize(__x.size());
    //....
    ,发现是内存拷贝构造,这也就解释清楚
       std::vector<int> q0 = {0,1};
       std::vector<int> q1 = q0;
    
       q0.push_back(2);
    
        q1.push_back(3);
    
    
        print_vector(q0); // 0 1 2
        print_vector(q1); // 0 1 3
    STL 在不结合智能指针直接在栈中创建完全符合基础变量的使用,很好的配合了RALL机制,
    因此在使用局部变量的容器时要注意返回的不是引用会有性能损耗,但是使用引用可以避免,
    但是要确保生命周期足够长!这是rust教给我的(笑
  • 相关阅读:
    [ 基础 转义字符 ] HTML转义字符对照表
    CRM 启用或禁用自定义代码执行
    CRM Setstate plugin
    CRM HomePage.aspx
    CRM 403错误
    CRM 2016 js 奇怪现象
    CRM 日期类型的一些处理JS
    CRM JS 设置lookup字段 setSimpleLookupValue
    CRM 2016 级联过滤 类比省市县
    CRM合并事件
  • 原文地址:https://www.cnblogs.com/Addoil/p/15508422.html
Copyright © 2011-2022 走看看