Насколько я понимаю, в Rust требуется, чтобы объект, содержащий ссылку, имел строго более короткое время жизни, чем объект, на который он ссылается.
Однако, если я правильно понимаю, в стандарте C++ такого требования нет. Итак, я придумал головоломку:
#include
struct Chicken;
struct Egg;
// FYI: You can add any member functions / data members you want to this class.
struct Chicken
{
const Egg& egg;
};
// FYI: You can add any member functions / data members you want to this class.
struct Egg
{
const Chicken& chicken;
};
// DO NOT MODIFY.
bool testChickenAndEgg(const Chicken& chicken, const Egg& egg)
{
return (std::addressof(chicken.egg) == std::addressof(egg)) &&
(std::addressof(chicken) == std::addressof(egg.chicken));
}
// Puzzle: construct such objects chicken (of type Chicken) and egg (of type Egg)
// that testChickenAndEgg(chicken, egg) == true.
// Rules:
// 1. Removing/commenting out existing code is not allowed.
// 2. Overloading testChickenAndEgg is not allowed.
// 3. Non-standard code / undefined behavior is not allowed.
Я нашел одно решение, но мне интересно, есть ли другие.
Решение:
struct Egg;
struct Chicken {
Chicken(Egg** pp_egg);
const Egg& egg;
};
struct Egg {
const Chicken& chicken;
};
Chicken::Chicken(Egg** pp_egg):
egg(*((*pp_egg) = new Egg{*this}))
{}
void solution() {
Egg* egg = nullptr;
Chicken chicken {&egg};
testChickenAndEgg(chicken, *egg);
delete egg;
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... uzzle-in-c