c++ template学习记录

使用模板将实际类型的指针进行封装

当变量退出作用域 自动delete

// 1111.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h" template <typename T>
class Holder {
private:
T* ptr; // refers to the object it holds (if any) public:
// default constructor: let the holder refer to nothing
Holder() : ptr(0) {
} // constructor for a pointer: let the holder refer to where the pointer refers
explicit Holder(T* p) : ptr(p) {
} // destructor: releases the object to which it refers (if any)
~Holder() {
delete ptr;
} // assignment of new pointer
Holder<T>& operator= (T* p) {
delete ptr;
ptr = p;
return *this;
} // pointer operators
T& operator* () const {
return *ptr;
} T* operator-> () const {
return ptr;
} // get referenced object (if any)
T* get() const {
return ptr;
} // release ownership of referenced object
void release() {
ptr = 0;
} // exchange ownership with other holder
void exchange_with(Holder<T>& h) {
std::swap(ptr, h.ptr);
} // exchange ownership with other pointer
void exchange_with(T*& p) {
std::swap(ptr, p);
} private:
// no copying and copy assignment allowed
Holder(Holder<T> const&);
Holder<T>& operator= (Holder<T> const&);
}; class Something {
public:
void perform() const {
}
}; void do_two_things()
{
Holder<Something> first(new Something);
first->perform(); Holder<Something> second(new Something);
second->perform();
} int main()
{
do_two_things();
}

  

// 1111111.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <stddef.h>
#include <iostream>
#include <vector> using namespace std; size_t* alloc_counter()
{
return ::new size_t;
} void dealloc_counter(size_t* ptr)
{
::delete ptr;
} class SimpleReferenceCount {
private:
size_t* counter; // the allocated counter
public:
SimpleReferenceCount() {
counter = NULL;
} // default copy constructor and copy-assignment operator
// are fine in that they just copy the shared counter public:
// allocate the counter and initialize its value to one:
template<typename T> void init(T*) {
counter = alloc_counter();
*counter = 1;
} // dispose of the counter:
template<typename T> void dispose(T*) {
dealloc_counter(counter);
} // increment by one:
template<typename T> void increment(T*) {
++*counter;
} // decrement by one:
template<typename T> void decrement(T*) {
--*counter;
} // test for zero:
template<typename T> bool is_zero(T*) {
return *counter == 0;
}
}; class StandardArrayPolicy {
public:
template<typename T> void dispose(T* array) {
delete[] array;
}
}; class StandardObjectPolicy {
public:
template<typename T> void dispose(T* object) {
delete object;
}
}; template<typename T,
typename CounterPolicy = SimpleReferenceCount,
typename ObjectPolicy = StandardObjectPolicy>
class CountingPtr : private CounterPolicy, private ObjectPolicy {
private:
// shortcuts:
typedef CounterPolicy CP;
typedef ObjectPolicy OP; T* object_pointed_to; // the object referred to (or NULL if none) public:
// default constructor (no explicit initialization):
CountingPtr() {
this->object_pointed_to = NULL;
} // a converting constructor (from a built-in pointer):
explicit CountingPtr(T* p) {
this->init(p); // init with ordinary pointer
} // copy constructor:
CountingPtr(CountingPtr<T, CP, OP> const& cp)
: CP((CP const&)cp), // copy policies
OP((OP const&)cp) {
this->attach(cp); // copy pointer and increment counter
} // destructor:
~CountingPtr() {
this->detach(); // decrement counter
// (and dispose counter if last owner)
} // assignment of a built-in pointer
CountingPtr<T, CP, OP>& operator= (T* p) {
// no counting pointer should point to *p yet:
assert(p != this->object_pointed_to);
this->detach(); // decrement counter
// (and dispose counter if last owner)
this->init(p); // init with ordinary pointer
return *this;
} // copy assignment (beware of self-assignment):
CountingPtr<T, CP, OP>&
operator= (CountingPtr<T, CP, OP> const& cp) {
if (this->object_pointed_to != cp.object_pointed_to) {
this->detach(); // decrement counter
// (and dispose counter if last owner)
CP::operator=((CP const&)cp); // assign policies
OP::operator=((OP const&)cp);
this->attach(cp); // copy pointer and increment counter
}
return *this;
} // the operators that make this a smart pointer:
T* operator-> () const {
return this->object_pointed_to;
} T& operator* () const {
return *this->object_pointed_to;
} // additional interfaces will be added later
//... private:
// helpers:
// - init with ordinary pointer (if any)
void init(T* p) {
if (p != NULL) {
CounterPolicy::init(p);
}
this->object_pointed_to = p;
} // - copy pointer and increment counter (if any)
void attach(CountingPtr<T, CP, OP> const& cp) {
this->object_pointed_to = cp.object_pointed_to;
if (cp.object_pointed_to != NULL) {
CounterPolicy::increment(cp.object_pointed_to);
}
} // - decrement counter (and dispose counter if last owner)
void detach() {
if (this->object_pointed_to != NULL) {
CounterPolicy::decrement(this->object_pointed_to);
if (CounterPolicy::is_zero(this->object_pointed_to)) {
// dispose counter, if necessary:
CounterPolicy::dispose(this->object_pointed_to);
// use object policy to dispose the object pointed to:
ObjectPolicy::dispose(this->object_pointed_to);
}
}
}
}; void test1()
{
std::cout << "\ntest1():\n";
CountingPtr<int> p0;
{
CountingPtr<int> p1(new int(42));
std::cout << "*p1: " << *p1 << std::endl; *p1 = 17;
std::cout << "*p1: " << *p1 << std::endl; CountingPtr<int> p2 = p1;
std::cout << "*p2: " << *p2 << std::endl; *p1 = 33;
std::cout << "*p2: " << *p2 << std::endl; p0 = p2;
std::cout << "*p0: " << *p0 << std::endl; ++*p0;
++*p1;
++*p2;
std::cout << "*p0: " << *p0 << std::endl;
std::cout << "*p1: " << *p1 << std::endl;
std::cout << "*p2: " << *p2 << std::endl;
}
std::cout << "after block: *p0: " << *p0 << std::endl;
} void test2()
{
std::cout << "\ntest2():\n";
{ CountingPtr<int> p0(new int(42));
CountingPtr<int> p2 = p0;
}
CountingPtr<int> p1(new int(42)); std::cout << "qqq" << std::endl; std::vector<CountingPtr<int> > coll;
std::cout << "qqq" << std::endl;
coll.push_back(p1);
std::cout << "qqq" << std::endl;
coll.push_back(p1);
std::cout << "qqq" << std::endl; std::cout << "qqq" << std::endl; ++*p1;
++*coll[0];
std::cout << *coll[1] << std::endl;
} int main()
{
test1();
test2();
}

  

模板学习实践二 pointer的更多相关文章

  1. 模板学习实践三 functor

    #include <iostream>#include <typeinfo> void foo(){ std::cout << "foo() called ...

  2. 《Hadoop学习之路》学习实践二——配置idea远程调试hadoop

    背景:在上篇文章中按照大神“扎心了老铁”的博客,在服务器上搭建了hadoop的伪分布式环境.大神的博客上是使用eclipse来调试,但是我入门以来一直用的是idea,eclipse已经不习惯,于是便摸 ...

  3. 模板学习实践一 accumulationtraits

    // 11111.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> #include &l ...

  4. 【前端,干货】react and redux教程学习实践(二)。

    前言 这篇博文接 [前端]react and redux教程学习实践,浅显易懂的实践学习方法. ,上一篇简略的做了一个redux的初级demo,今天深入的学习了一些新的.有用的,可以在生产项目中使用的 ...

  5. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  6. Appium学习实践(二)Python简单脚本以及元素的属性设置

    1.简单的Python脚本 Appium中的设置与Appium学习实践(一)简易运行Appium中的一致 Launch后,执行脚本 #coding:utf-8 import unittest impo ...

  7. linux内核分析实践二学习笔记

    Linux实践二--内核模块的编译 标签(空格分隔): 20135328陈都 理解内核的作用 Linux内核[kernel]是整个操作系统的最底层,它负责整个硬件的驱动,以及提供各种系统所需的核心功能 ...

  8. 第04项目:淘淘商城(SpringMVC+Spring+Mybatis) 的学习实践总结【第四天】

    https://pan.baidu.com/s/1bptYGAb#list/path=%2F&parentPath=%2Fsharelink389619878-229862621083040 ...

  9. Nagios学习实践系列——基本安装篇

    开篇介绍 最近由于工作需要,学习研究了一下Nagios的安装.配置.使用,关于Nagios的介绍,可以参考我上篇随笔Nagios学习实践系列——产品介绍篇 实验环境 操作系统:Red Hat Ente ...

随机推荐

  1. os.rename 和os.replace

    f1 = open("hello.txt","w") f1.write("hello,my name is bobo.") f1.close ...

  2. 51nod1340 地铁环线

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1340 设x为环线的长度,要判断某个特定的x是否可行,不难将题目转为差分约 ...

  3. 基于MNIST数据集使用TensorFlow训练一个包含一个隐含层的全连接神经网络

    包含一个隐含层的全连接神经网络结构如下: 包含一个隐含层的神经网络结构图 以MNIST数据集为例,以上结构的神经网络训练如下: #coding=utf-8 from tensorflow.exampl ...

  4. Lepus监控之安装部署

    PHP和Python都是跨平台的语言,所以理论上系统应该可以支持在不同的平台上运行.但是由于时间和精力以及资源有限,目前天兔系统只测试完善了Centos/RedHat系统的支持.我们目前提供的技术支持 ...

  5. 三元运算&匿名函数lambda

    lambda # 语法: # 参数 : 返回值 # 1.不带参数的lambda表达式 def func(): return '开挂的人生不需要解释' func = lambda : '开挂的人上不需要 ...

  6. .NET MVC 控制器和行为

    行为就是可访问方法(public) 行为返回类型必须是 ActionResult 或者其派生类,基本上返回类型为以下四种之一 View(视图路径) Json(对象或者对象集合) Content(字符串 ...

  7. 深度学习原理与框架-Tfrecord数据集的制作 1.tf.train.Examples(数据转换为二进制) 3.tf.image.encode_jpeg(解码图片加码成jpeg) 4.tf.train.Coordinator(构建多线程通道) 5.threading.Thread(建立单线程) 6.tf.python_io.TFR(TFR读入器)

    1. 配套使用: tf.train.Examples将数据转换为二进制,提升IO效率和方便管理 对于int类型 : tf.train.Examples(features=tf.train.Featur ...

  8. python_08 函数式编程、高阶函数、map、filter、reduce函数、内置函数

    函数式编程 编程方法论: 1.面向过程 找到解决问题的入口,按照一个固定的流程去模拟解决问题的流程 (1).搜索目标,用户输入(配偶要求),按照要求到数据结构内检索合适的任务 (2)表白,表白成功进入 ...

  9. Microsoft DQS sqlException 0x80131904 - SetDataQualitySessionPhaseTwo

    遇到这个问题的原因可以从报错信息看出来,大概率是.net framework的问题 可以尝试如下解决途径 1. regenerate .net Assemble for DQS 2. 如果步骤一无法解 ...

  10. 应用脚手架创建一个React项目

    安装脚手架,这里会自动安装到你的nodejs里面 npm install create-react-app -g 进入创建目录 我这里创建一个为 react03的项目,等待下载..... create ...