Item 18: Make interfaces easy to use correctly and hard to use incorrectly(Effective C++)
-
Good interfaces are easy to use correctly and hard to use incorrectly. Your should strive for these characteristics in all your interfaces.
-
Ways to facilitate correct use include consistency in interfaces and behavioral compatibility with built-in types.
-
Ways to prevent errors include creating new types, restricting operations on types, constraining object values, and eliminating client resource management responsibilities.
-
TR1::shared_ptr supports custom deleters. This prevents the cross-DLL problem, can be used to automatically unlock mutexes (see Item 14), etc.
1 #include <iostream>
2 #include <string>
3 #include <boost/shared_ptr.hpp>
4 #include <fstream>
5 using namespace std;
6
7 class Test
8 {
9 public:
10 void test(Test* t)
11 {
12 ofstream out("1.txt");
13 out << "test in class" << endl;
14 out.close();
15 }
16 };
17
18 void test(Test* t)
19 {
20 ofstream out("1.txt");
21 out << "test in global" << endl;
22 out.close();
23 }
24
25 void a()
26 {
27 Test* t = new Test();
28 //void (Test::*funcPtr)(Test*) = &Test::test;
29 boost::shared_ptr<Test> sp(t, test);
30 }
31
32 int main()
33 {
34 a();
35
36 cin.get();
37 return 0;
38 }
2 #include <string>
3 #include <boost/shared_ptr.hpp>
4 #include <fstream>
5 using namespace std;
6
7 class Test
8 {
9 public:
10 void test(Test* t)
11 {
12 ofstream out("1.txt");
13 out << "test in class" << endl;
14 out.close();
15 }
16 };
17
18 void test(Test* t)
19 {
20 ofstream out("1.txt");
21 out << "test in global" << endl;
22 out.close();
23 }
24
25 void a()
26 {
27 Test* t = new Test();
28 //void (Test::*funcPtr)(Test*) = &Test::test;
29 boost::shared_ptr<Test> sp(t, test);
30 }
31
32 int main()
33 {
34 a();
35
36 cin.get();
37 return 0;
38 }