我正在尝试调整一些预先存在的代码以利用 std::shared_ptr<...>。它是一个“消息传递系统”,因此基本上下文是:
公共方法:
void writeReport(std::shared_ptr<const ReportBase> pReport) {
/* This is a public method for writing a report. I might do
additional stuff in here but end by forwarding to the
private method. */
writeReport_(pReport);
}
Run Code Online (Sandbox Code Playgroud)
私有方法:
void writeReport_(std::shared_ptr<const ReportBase> pReport) {
if( certain conditions )
processReport_(pReport);
writeBytes_(serialize(pReport));
}
Run Code Online (Sandbox Code Playgroud)
加工方法:
void processReport_(std::shared_ptr<const ReportBase> pReport) {
processReportImpl(pReport);
if( certain other conditions )
reportDeque_.push_back(pReport);
}
Run Code Online (Sandbox Code Playgroud)
例如,在上述伪代码中,processReport_(...) 可能是在某些条件下想要实际存储记录的唯一方法。其他方法仅对所指向的对象的内容感兴趣。因此,如果不是有时需要复制shared_ptr processReport_(...)(即“存储”记录),我只需传递const ReportBase *给所有嵌套函数并避免按值传递的开销(即使用计数增量) 。
因此,我想通过std::shared_ptr<const ReportBase>&(也许&&在适当的情况下),但想阻止一些流氓嵌套方法实际修改指针指向的内容。所以我想我想通过const std::shared_ptr<const …