support bazel complie this project and format code.

This commit is contained in:
zhangxing
2023-03-30 00:15:11 +08:00
committed by light-city
parent 1f86192576
commit 7529ae3a55
636 changed files with 10025 additions and 9387 deletions

View File

@@ -0,0 +1,21 @@
# please run `bazel run //learn_class/modern_cpp_30/RAII:stack`
# please run `bazel run //learn_class/modern_cpp_30/RAII:heap`
# please run `bazel run //learn_class/modern_cpp_30/RAII:RAII`
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "stack",
srcs = ["stack.cpp"],
copts = ["-std=c++11"],
)
cc_binary(
name = "heap",
srcs = ["heap.cpp"],
copts = ["-std=c++11"],
)
cc_binary(
name = "RAII",
srcs = ["RAII.cpp"],
copts = ["-std=c++11"],
)

View File

@@ -0,0 +1,82 @@
#include <fstream>
#include <iostream>
#include <mutex>
using namespace std;
enum class shape_type {
circle,
triangle,
rectangle,
};
class shape {
public:
shape() { cout << "shape" << endl; }
virtual void print() { cout << "I am shape" << endl; }
virtual ~shape() {}
};
class circle : public shape {
public:
circle() { cout << "circle" << endl; }
void print() { cout << "I am circle" << endl; }
};
class triangle : public shape {
public:
triangle() { cout << "triangle" << endl; }
void print() { cout << "I am triangle" << endl; }
};
class rectangle : public shape {
public:
rectangle() { cout << "rectangle" << endl; }
void print() { cout << "I am rectangle" << endl; }
};
// 利用多态 上转 如果返回值为shape,会存在对象切片问题。
shape *create_shape(shape_type type) {
switch (type) {
case shape_type::circle:
return new circle();
case shape_type::triangle:
return new triangle();
case shape_type::rectangle:
return new rectangle();
}
}
class shape_wrapper {
public:
explicit shape_wrapper(shape *ptr = nullptr) : ptr_(ptr) {}
~shape_wrapper() { delete ptr_; }
shape *get() const { return ptr_; }
private:
shape *ptr_;
};
void foo() {
shape_wrapper ptr(create_shape(shape_type::circle));
ptr.get()->print();
}
int main() {
// 第一种方式
shape *sp = create_shape(shape_type::circle);
sp->print();
delete sp;
// 第二种方式
foo();
return 0;
}

View File

@@ -0,0 +1,35 @@
#include <iostream>
using namespace std;
class bar {};
// java 程序员风格
void foo() {
cout << "method 1" << endl;
bar *ptr = new bar();
delete ptr;
}
bar *make_bar() {
bar *ptr = nullptr;
try {
ptr = new bar();
} catch (...) {
delete ptr;
throw;
}
return ptr;
}
// 独立出函数 分配和释放不在一个函数里
void foo1() {
cout << "method 2" << endl;
bar *ptr = make_bar();
delete ptr;
}
int main() {
foo();
foo1();
return 0;
}

View File

@@ -0,0 +1,23 @@
//
// Created by light on 19-12-9.
//
#include <iostream>
class Obj {
public:
Obj() { puts("Obj()"); }
~Obj() { puts("~Obj()"); }
};
void foo(int n) {
Obj obj;
if (n == 42)
throw "life, the universe and everything";
}
// 不管是否发生了异常obj 的析构函数都会得到执行。
int main() {
try {
foo(41);
foo(42);
} catch (const char *s) {
puts(s);
}
}