Created
April 27, 2021 23:45
-
-
Save poseidon4o/fe4662b9067dcceb43225fee6a26740d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template <typename T> | |
struct ScopedPointer { | |
private: | |
T *ptr; | |
public: | |
ScopedPointer(const ScopedPointer &) = delete; | |
ScopedPointer &operator=(const ScopedPointer &) = delete; | |
ScopedPointer(T *ptr) | |
: ptr(ptr) {} | |
~ScopedPointer() { | |
delete ptr; | |
} | |
T &operator*() { | |
return *ptr; | |
} | |
}; | |
// TODO: implement this, without function overloading, use templates and SFINAE | |
template <typename T> | |
void deepCopy(T &dest, T &source) {} | |
int main() { | |
{ | |
ScopedPointer<int> x(new int{100}), y(new int{2}); | |
std::cout << "x = " << *x << " y = " << *y << std::endl; | |
deepCopy(x, y); | |
std::cout << "x = " << *x << " y = " << *y << std::endl; | |
} | |
{ | |
float x = 3.14f, y = 17.3f; | |
std::cout << "x = " << x << " y = " << y << std::endl; | |
deepCopy(x, y); | |
std::cout << "x = " << x << " y = " << y << std::endl; | |
} | |
{ | |
double vals[2] = {100.1, 200.2}; | |
double *x = &vals[0]; | |
double *y = &vals[1]; | |
std::cout << "x = " << *x << " y = " << *y << std::endl; | |
deepCopy(x, y); | |
std::cout << "x = " << *x << " y = " << *y << std::endl; | |
} | |
/* Expected output: | |
* x = 100 y = 2 | |
* x = 2 y = 2 | |
* x = 3.14 y = 17.3 | |
* x = 17.3 y = 17.3 | |
* x = 100.1 y = 200.2 | |
* x = 200.2 y = 200.2 | |
*/ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment