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教给我的(笑

 

posted @ 2021-11-04 15:35  州长在手  阅读(34)  评论(0编辑  收藏  举报