首先 C++这个语言表达力及其丰富,以至于初学者不知所措,经常会看到不认识的语法,这是在其它语言不太会经历到的。 但是它所有的复杂性都服务于一个目标,抽象(abstraction)。抽象是一个高级的思考过程,它试图从杂乱无章中找到模式。
不知各位有没有用过 boost json ,json 仅有几种有限的数据类型,大部分语言有类(class),用它来抽象这些数据类型也挺不错,c++也是 OOP 。 但是 C++还有 std::variant,就是说如果一个东西只可能有固定的几个类型,那么用std::variant来抽象更恰当(也可能更快,更不容易错,或者无法错)。
其它比如shared_from_this等都是为解决问题而生,如果你没有碰到问题,那么你就不会深入理解shared_from_this。它是为了在异步环境中让对象自己保持活着,不然异步回调时如果对象已经销毁,就会 UAF 。
namespace certctrl {
class UpdateHandler : public IHandler,
public std::enable_shared_from_this[U] {
private:
certctrl::ICertctrlConfigProvider &config_provider_;
customio::ConsoleOutput &output_;
client_async::HttpClientManager &http_client_;
certctrl::CliCtx &cli_ctx_;
std::shared_ptr update_checker_;
// Platform detection
std::string detect_platform();
std::string detect_architecture();
// Update workflow steps
monad::IO[b] check_for_updates(const std::string ¤t_version);
monad::IO[b] confirm_update();
monad::IO perform_update();
monad::IO download_update(const std::string &download_url);
monad::IO install_update(const std::string &downloaded_file);
monad::IO backup_current_binary();
monad::IO replace_binary(const std::string &new_binary_path);
// Helper methods
std::string get_current_binary_path();
std::string generate_backup_path();
bool verify_downloaded_file(const std::string &file_path, const std::string &checksum_url);
public:
UpdateHandler(certctrl::ICertctrlConfigProvider &config_provider,
customio::ConsoleOutput &output,
client_async::HttpClientManager &http_client,
certctrl::CliCtx &cli_ctx,
std::shared_ptr update_checker);
std::string command() const override;
monad::IO start() override;
};
}
当然这里仅仅举几个例子,每一个特性都是为解决问题而设计的。
说到为什么年长者更喜欢 c++,我估计可能和大脑的抽象能力相关,我不是脑科学专家,我还问了 chatgpt ,它的答复:
情况 结果
纯逻辑、非经验性的抽象任务(数学推理、形状类比、无语言图形测试) 年轻人通常更强
基于经验的抽象总结、模式识别 年长者可能更强
需要同时抽象 + 处理大量新信息的任务 年轻人更快
需要抽象 + 基于经验的判断 年长者表现可能更佳
所以更准确的结论应该是,经验丰富的编程者可能会选择 C++。 如果你是初学者,不要为 C++的复杂度困扰,这需要一个过程,一个进步的过程。


