我有一个A像这样的 C++ 类:
// third-party classes / methods, unable to change\nclass C {};\nclass B {\npublic:\n C* getC();\n};\nB* legacyAPIToGetB(const char*);\n\n// the target class\nclass A {\npublic:\n A() {\n // not using initialization lists\n // because something have to be calculated prior B construction\n b = std::unique_ptr<B>(legacyAPIToGetB("calculated value"));\n // throw an exception (don\'t construct A) if B cannot be constructed\n if (!b) throw std::exception{"Cannot get B"};\n\n c = std::unique_ptr<C>(b->getC());\n if (!c) throw std::exception{"Cannot get C"};\n }\n\n std::unique_ptr<B> b = nullptr;\n …Run Code Online (Sandbox Code Playgroud)