Created
September 27, 2018 08:38
-
-
Save Rseding91/86238ad3eae657821e23e4e72637a483 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
struct base | |
{ | |
enum class Type | |
{ | |
A, | |
B, | |
C | |
}; | |
virtual ~base() = default; | |
virtual Type getType() const = 0; | |
}; | |
struct A final : base | |
{ | |
virtual Type getType() const override { return Type::A; } | |
}; | |
struct B final : base | |
{ | |
virtual Type getType() const override { return Type::B; } | |
}; | |
struct C final : base | |
{ | |
virtual Type getType() const override { return Type::C; } | |
}; | |
int foo(int rng) | |
{ | |
std::unique_ptr<base> instance; | |
switch (rng) | |
{ | |
case 1: instance = std::make_unique<A>(); break; | |
case 2: instance = std::make_unique<B>(); break; | |
case 3: instance = std::make_unique<C>(); break; | |
default: return 0; | |
} | |
// -- some barrier here that prevents the compiler from knowing how instance was populated | |
// that prevents mapping rng -> return value and skipping the allocation completely -- | |
// for example: populate instance from input at tick 1, then check at tick 2. | |
if (instance->getType() == base::Type::A) | |
return 3; | |
else if (instance->getType() == base::Type::B) | |
return 2; | |
else if (instance->getType() == base::Type::C) | |
return 1; | |
else | |
return 0; // malformed/memory corruption/compiler bug - this should never be possible and could be treated as a terminate() if it happened | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment