Last active
April 26, 2019 23:29
-
-
Save jthemphill/4b5419e3c29161580450b4c32a3a0cbc 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
// % g++ --std=c++14 accidentalcopy.cc -o accidentalcopy | |
// % ./accidentalcopy | |
// This prints the output: | |
// | |
// 42 = 42 | |
// 42 = 42 | |
// accidentalcopy(13656,0x117fc45c0) malloc: *** error for object 0x7fd967402b20: pointer being freed was not allocated | |
// accidentalcopy(13656,0x117fc45c0) malloc: *** set a breakpoint in malloc_error_break to debug | |
#include <iostream> | |
class Repo { | |
public: | |
Repo() | |
: fortyTwo_{new int{42}} {} | |
~Repo() { | |
std::cout << "42 = " << *fortyTwo_ << std::endl; | |
delete fortyTwo_; | |
} | |
// I define this a little later | |
static Repo& get(); | |
int* fortyTwo_ = nullptr; | |
}; | |
// This is the only Repo that's supposed to exist | |
Repo s_repo; | |
Repo& Repo::get() { | |
return s_repo; | |
} | |
int main() { | |
// Should be `Repo& repo1 = Repo::get()` | |
// Leaving the `&` off makes an extra copy, which means we delete fortyTwo_ twice... | |
Repo repo1 = Repo::get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment