Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is an example of the pimpl idiom using smart pointers.
cmake_minimum_required(VERSION 3.16)
project(pimpl_idiom)
set(CMAKE_CXX_STANDARD 17)
add_library(timer timer.cpp)
add_executable(pimpl_idiom main.cpp)
target_link_libraries(pimpl_idiom timer)
#include <iostream>
#include <chrono>
#include <thread>
#include "timer.h"
int main() {
AutoTimer at("Angelos");
at.UpdateName("Aris");
std::this_thread::sleep_for(std::chrono::seconds (2));
return 0;
}
//
// Created by angelos on 30/05/2020.
//
#include "timer.h"
#include <iostream>
#if WIN32
#include <windows.h>
#else
#include <ctime>
#endif
class AutoTimer::TimerImpl {
public:
[[nodiscard]] double GetElapsed() const {
#ifdef WIN32
return (GetTickCounts() - mStartTime) / 1e3;
#else
time_t end_time{};
time(&end_time);
return difftime(end_time, mStartTime);
#endif
}
std::string mName;
#ifdef WIN32
DWORD mStartTime;
#else
time_t mStartTime{};
#endif
};
AutoTimer::AutoTimer(std::string_view name) : mImpl{new AutoTimer::TimerImpl} {
mImpl->mName = name;
#ifdef WIN32
mImpl->mStartTime = GetTickCount();
#else
time(&mImpl->mStartTime);
#endif
}
AutoTimer::~AutoTimer() {
std::cout << mImpl->mName << ": took " << mImpl->GetElapsed() << " secs" << std::endl;
}
void AutoTimer::UpdateName(std::string_view new_name) const {
mImpl->mName = new_name;
}
//
// Created by angelos on 30/05/2020.
//
#ifndef PIMPL_IDIOM_TIMER_H
#define PIMPL_IDIOM_TIMER_H
#include <memory>
#include <string_view>
class AutoTimer {
public:
explicit AutoTimer(std::string_view name);
~AutoTimer();
void UpdateName(std::string_view new_name) const;
private:
class TimerImpl;
std::unique_ptr<TimerImpl> mImpl;
};
#endif//PIMPL_IDIOM_TIMER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.