Skip to content

Commit

Permalink
add smart-point
Browse files Browse the repository at this point in the history
  • Loading branch information
yangsoon committed Jun 26, 2020
1 parent f0cc41e commit 7b80321
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion C++Primer/Template/com.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ int compare(const T &v1, const T &v2) {
}

int main() {

cout << compare<int>(1,2);
}
29 changes: 29 additions & 0 deletions C++Primer/smart_point/strblob.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "strblob.h"

// make_shared 在动态内存中分配一个对象并初始化它
StrBlob::StrBlob(): data(std::make_shared<std::vector<std::string>>()) {};

StrBlob::StrBlob(std::initializer_list<std::string> il): data(std::make_shared<std::vector<std::string>>(il)){};

void StrBlob::check(size_type i, const std::string &msg) const {
if (i >= data->size()) {
throw std::out_of_range(msg);
}
}

std::string& StrBlob::front() {
check(0, "front on empty StrBlob");
return data->front();
}

std::string& StrBlob::back() {
check(0, "back on empty StrBlob");
return data->back();
}

void StrBlob::pop_back() {
check(0, "pop_back on empty StrBlob");
data->pop_back();
}


20 changes: 20 additions & 0 deletions C++Primer/smart_point/strblob.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <iostream>
#include <memory>
#include <vector>
#include <string>

class StrBlob {
public:
typedef std::vector<std::string>::size_type size_type;
StrBlob();
StrBlob(std::initializer_list<std::string> il);
size_type size() const {return data->size();}
bool empty() const {return data->empty();}
void push_back(const std::string &t) {data->push_back(t)};
void pop_back();
std::string& front();
std::string& back();
private:
std::shared_ptr<std::vector<std::string>> data;
void check(size_type i, const std::string &msg) const;
};
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 7b80321

Please sign in to comment.