Humboldt-Universität zu Berlin - Mathematisch-Naturwissenschaftliche Fakultät - Systemanalyse

Beispiel bessere Zeiger

text/x-c++src pointer.cpp — 1.9 KB

Dateiinhalt

//
//  main.cpp
//  pointer
//
//  Created by Klaus Ahrens on 26.10.12.
//  Copyright (c) 2012 Klaus Ahrens. All rights reserved.
//

#include <iostream>
#include <chrono>
#include <string>
#include <memory>
#include <cassert>

class Timer {
    std::chrono::steady_clock::time_point start;
    std::string what;
public:
    Timer(std::string s): start(std::chrono::steady_clock::now()), what(s) {}
    ~Timer() {
        auto duration = std::chrono::steady_clock::now() - start;
        std::cout << what+":\t" << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " ms" << std::endl;
    }
};

const auto N = 2000000;

int main(int argc, const char * argv[])
{
    std::cout<<1["]<<2["]<< std::endl;
    {
        Timer t ("raw pointer");
        for (int i = 0; i < N; ++i) {
            int* pi = new int;
            *pi = 42;
            int* qi = pi;
            ++*qi;
            assert(*pi==43);
            assert(*qi==43);
            delete pi; // unsafe !
        }
    }
    {
        Timer t ("unique pointer");
        for (int i = 0; i < N; ++i) {
            std::unique_ptr<int> pi (new int);
            *pi = 42; // safe, no leak
            std::unique_ptr<int> qi = std::move(pi); // take ownership
            ++*qi;
            assert(pi.get()==nullptr);
            assert(pi==nullptr);
            assert(!pi);
            assert(*qi==43);
        }
    }
    {
        Timer t ("shared pointer");
        for (int i = 0; i < N; ++i) {
            std::shared_ptr<int> pi (new int);
            *pi = 42;
            std::shared_ptr<int> qi = pi;
            ++*qi;
            assert(*pi==43);
            assert(*qi==43);
        }
    }
    {
        Timer t ("made pointer");
        for (int i = 0; i < N; ++i) {
            auto pi = std::make_shared<int>(42);
            std::shared_ptr<int> qi = pi;
            ++*qi;
            assert(*pi==43);
            assert(*qi==43);
        }
    }

}