// 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
}