various pointer
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1// Demo um C-Pointer, unique_ptr und shared_ptr zu zeigen.
2
3#include <cmath>
4#include <iostream>
5#include <memory> // shared_ptr
6using namespace std;
7
8// Simple class
9class Basis
10{
11public:
12 Basis(double a, double b) : _s(sqrt(a*a+b*b)) {}
13 double fkt() const {return _s;}
14private:
15 double _s;
16};
17
18int main()
19{
20 {
21 cout << "\n#### Demo C-Pointer and dynamic memory ####\n";
22 Basis* a = new Basis(3,4); // allocate memory and init instance
23
24 Basis* b=a; // copies the pointer, n o t the data
25 cout << b->fkt() << endl;
26
27 delete a; // free the allocated memory
28 delete b; // WRONG: free already deallocated memory
29 }
30
31 {
32 cout << "\n#### Demo shared pointer ####\n";
33// shared_ptr<Basis> a(new Basis(3,4)); // allocate memory
34 auto a = make_shared<Basis>(3,4);
35
36 shared_ptr<Basis> b=a; // copies the pointer, n o t the data
37 cout << b->fkt() << endl;
38 cout << endl;
39 } // destructor of shared_ptr frees the allocated memory (only once !)
40
41 {
42 cout << "\n#### Demo unique pointer ####\n";
43// unique_ptr<Basis> a(new Basis(3,4)); // allocate memory
44 auto a = make_unique<Basis>(3,4); // C++-14
45
46 //unique_ptr<Basis> b=a; // copy not possible with unique_ptr
47 unique_ptr<Basis>& b=a; // but reference is possible
48 cout << b->fkt() << endl;
49 cout << endl;
50 } // destructor of unique_ptr frees the allocated memory (only once !)
51
52 {
53 cout << "\n#### Demo raw pointer to shared pointer ####\n";
54// https://stackoverflow.com/questions/4665266/creating-shared-ptr-from-raw-pointer
55 // Don't do it, or do it in that way:
56 shared_ptr<Basis> a(new Basis(3,4));
57 }
58
59 return 0;
60}
61
62
63/*
64 g++ -pedantic -std=c++14 -Weffc++ -Wall -Wextra -pedantic -Wswitch-default -Wfloat-equal -Wundef -Wredundant-decls -Winit-self -Wshadow -Wparentheses -Wshadow -Wunreachable-code -Wuninitialized -Wmaybe-uninitialized *.cpp
65 cppcheck --enable=all --inconclusive --std=c++11 --std=posix --suppress=missingIncludeSystem *.cpp
66 clang++ -std=c++14 -fsyntax-only -Wdocumentation -Wconversion -Wshadow -Wfloat-conversion -Wno-shorten-64-to-32 -Wno-sign-conversion -pedantic *.cpp
67 clang++ -std=c++14 -Weverything -Wno-c++98-compat -Wno-shorten-64-to-32 -Wno-sign-conversion -Wno-padded *.cpp
68 clang++ -cc1 --help
69 icpc -std=c++14 -Wall -Wextra -pedantic *.cpp
70*/
Definition main.cpp:10
Basis(double a, double b)
Definition main.cpp:12
double fkt() const
Definition main.cpp:13
int main()
Definition main.cpp:18