forked from taku910/crfpp
-
Notifications
You must be signed in to change notification settings - Fork 11
/
scoped_ptr.h
97 lines (86 loc) · 2.37 KB
/
scoped_ptr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// CRF++ -- Yet Another CRF toolkit
//
// $Id: scoped_ptr.h 1588 2007-02-12 09:03:39Z taku $;
//
// Copyright(C) 2005-2007 Taku Kudo <[email protected]>
//
#ifndef CRFPP_SCOPED_PTR_H_
#define CRFPP_SCOPED_PTR_H_
#include <cstring>
#include <string>
namespace CRFPP {
template<class T> class scoped_ptr {
private:
T * ptr_;
scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &);
typedef scoped_ptr<T> this_type;
public:
typedef T element_type;
explicit scoped_ptr(T * p = 0): ptr_(p) {}
virtual ~scoped_ptr() { delete ptr_; }
void reset(T * p = 0) {
delete ptr_;
ptr_ = p;
}
T & operator*() const { return *ptr_; }
T * operator->() const { return ptr_; }
T * get() const { return ptr_; }
};
template<class T, int N> class scoped_fixed_array {
private:
T * ptr_;
size_t size_;
scoped_fixed_array(scoped_fixed_array const &);
scoped_fixed_array & operator= (scoped_fixed_array const &);
typedef scoped_fixed_array<T, N> this_type;
public:
typedef T element_type;
explicit scoped_fixed_array()
: ptr_(new T[N]), size_(N) {}
virtual ~scoped_fixed_array() { delete [] ptr_; }
size_t size() const { return size_; }
T & operator*() const { return *ptr_; }
T * operator->() const { return ptr_; }
T * get() const { return ptr_; }
T & operator[](size_t i) const { return ptr_[i]; }
};
template<class T> class scoped_array {
private:
T * ptr_;
scoped_array(scoped_array const &);
scoped_array & operator=(scoped_array const &);
typedef scoped_array<T> this_type;
public:
typedef T element_type;
explicit scoped_array(T * p = 0): ptr_(p) {}
virtual ~scoped_array() { delete [] ptr_; }
void reset(T * p = 0) {
delete [] ptr_;
ptr_ = p;
}
T & operator*() const { return *ptr_; }
T * operator->() const { return ptr_; }
T * get() const { return ptr_; }
T & operator[](size_t i) const { return ptr_[i]; }
};
class scoped_string: public scoped_array<char> {
public:
explicit scoped_string() { reset_string(""); }
explicit scoped_string(const std::string &str) {
reset_string(str);
}
void reset_string(const std::string &str) {
char *p = new char[str.size() + 1];
strcpy(p, str.c_str());
reset(p);
}
void reset_string(const char *str) {
char *p = new char[strlen(str) + 1];
strcpy(p, str);
reset(p);
}
};
}
#endif