您的位置:首页 > 编程语言 > C语言/C++

C/C++中变量的内存分配和收回

2019-01-31 11:56 134 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/M_sdn/article/details/86713045

// C:     who mallocs who frees
// C++:   who news who deletes
// C++11: who owns who does nothing

class Bar {
    Public:
        Bar();
        void doSomething() const;
};

void fun1(const Bar& bar) {
    bar.doSomething(); // does NOT own bar and can NOT modify bar
}

void fun2(Bar* bar) {  // raw pointer => access, no ownership
    bar->doSomething();// does NOT own bar but can modify bar including assignment
    *bar = Bar();
}

void fun3(std::unique_ptr<Bar> bar) {
    bar->doSomething();// owns bar, and it will be automatically deleted when out of scope
}

void foo() {
    std::unique_ptr<Bar> bar(new Bar()); //foo owns object bar
    fun1(*bar);
    fun2(bar.get());        
    fun3(std::move(bar));   // foo transfers the ownship of bar to fun3
    assert(bar == nullptr); // bar no longer exists
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: