CS253: Software Development with C++

Spring 2018

Smart Pointers

See this page as a slide show

CS253 Smart Pointers

Overview

The Problem

#include "Loud.h"
int main(int argc, char **) {
    auto p = new Loud;
    if (argc < 5) {
        cerr << "Not enough arguments.\n";
        return 1;
    }
    delete p;
    return 0;
}
Loud::Loud()
Not enough arguments.

Three kinds of smart pointers

  1. unique_ptr if the thing has one owner
  2. shared_ptr if the thing has several owners
  3. weak_ptr for voyeurs & lurkers
  4. auto_ptr for people who use obsolete features

auto_ptr

unique_ptr

unique_ptr example #1

#include "Loud.h"

int main(int argc, char **) {
    unique_ptr<Loud> p(new Loud);
    if (argc < 5) {
        cerr << "Not enough arguments.\n";
        return 1;
    }
    // don’t need to delete
    return 0;
}
Loud::Loud()
Not enough arguments.
Loud::~Loud()

unique_ptr example #2

#include "Loud.h"

void foo() {
    unique_ptr<Loud> p(new Loud);
    throw "I am unhappy";
}

int main() {
    try {
        foo();
    }
    catch (const char *p) {
        cerr << p << '\n';
    }
    return 0;
}
Loud::Loud()
Loud::~Loud()
I am unhappy

shared_ptr

shared_ptr example

#include "Loud.h"
int main() {
    shared_ptr<Loud> p(new Loud);
    cout << p.use_count() << '\n';
    {
        cout << p.use_count() << '\n';
        auto q=p;
        cout << p.use_count() << '\n';
        cout << q.use_count() << '\n';
    }
    cout << p.use_count() << '\n';
}
Loud::Loud()
1
1
2
2
1
Loud::~Loud()

Weak Pointers

Weak Pointers

Weak Pointers

weak_ptr example

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

weak_ptr<int> wp;

void observe() {
    cout << "use_count=" << wp.use_count() << ": ";
    if (auto sp = wp.lock())
        cout << *sp << '\n';
    else
        cout << "wp is expired\n";
}

int main() {
    {
        shared_ptr<int> mem(new int(42));
        wp = mem;
        observe();
    }

    observe();
}
use_count=1: 42
use_count=0: wp is expired

weak_ptr: why?

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building