Antworten
Content |
Hier sind die Antworten zu den einzelnen Fragen:
-
Das erste Beispiel:
#include <iostream> class Vector2D { public: Vector2D() : x(0), y(0) { std::cout << "X: default constructor" << std::endl; } Vector2D(const Vector2D& other) = delete; Vector2D& operator=(const Vector2D& other) { std::cout << "X: assignment operator" << std::endl; x = other.x; y = other.y; return *this; } double x, y; }; int main() { Vector2D a; Vector2D b = a; }
theon$ g++ -Wall -c case06.cpp case06.cpp: In function 'int main()': case06.cpp:19:17: error: use of deleted function 'Vector2D::Vector2D(const Vector2D&)' 19 | Vector2D b = a; | ^ case06.cpp:8:7: note: declared here 8 | Vector2D(const Vector2D& other) = delete; | ^~~~~~~~ theon$
Da der Kopierkonstruktor entfernt wurde, können Objekte dieses Typs nicht mehr kopier-konstruiert werden. Zuweisungen sind allerdings noch möglich:
theon$ diff -U 2 case06.cpp case06-fixed.cpp --- case06.cpp 2018-05-03 11:58:32.000000000 +0200 +++ case06-fixed.cpp 2018-05-03 13:54:20.000000000 +0200 @@ -17,4 +17,4 @@ int main() { Vector2D a; - Vector2D b = a; + Vector2D b; b = a; } theon$ g++ -Wall -g -o case06-fixed case06-fixed.cpp theon$ ./case06-fixed X: default constructor X: default constructor X: assignment operator theon$
-
Beim zweiten Problem kopieren die vom Übersetzer erzeugten Methoden (Kopierkonstruktor und Zuweisungsoperator) nur den Zeiger, d.h. alle Variablen haben den gleichen Zeiger, den sie alle beim Abbau freigeben.
heim$ diff -U 2 data-on-heap.cpp data-on-heap-fixed.cpp --- data-on-heap.cpp 2018-05-03 14:10:01.000000000 +0200 +++ data-on-heap-fixed.cpp 2018-05-03 14:10:24.000000000 +0200 @@ -9,8 +9,18 @@ std::cout << "X: constructor with i = " << i << std::endl; } + X(const X& other) : data(new int{*other.data}) { + std::cout << "X: copy constructor with *other.data = " + << *other.data << std::endl; + } ~X() { std::cout << "X: destructor with *data = " << *data << std::endl; delete data; } + X& operator=(const X& other) { + std::cout << "X: assignment operator with *other.data = " + << *other.data << std::endl; + *data = *other.data; + return *this; + } private: int* data; heim$ g++-8.3 -Wall -g -o data-on-heap-fixed data-on-heap-fixed.cpp /usr/local/libexec/gcc/x86_64-pc-linux-gnu/8.3.0/cc1plus: error while loading shared libraries: libmpfr.so.4: cannot open shared object file: No such file or directory heim$ ./data-on-heap-fixed sh: 1: ./data-on-heap-fixed: not found heim$ valgrind ./data-on-heap-fixed valgrind: ./data-on-heap-fixed: No such file or directory heim$