我正在尝试调整一些预先存在的代码以利用 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 ReportBase>&阻止这种情况......
...但是,processReport_(...)我有时会想制作一份副本来存储记录。
这最终引出了我的问题......
const std::shared_ptr<...>到 a std::shared_ptr<...>?const创建了shared_ptr的整个控制块const?或者前导const仅适用于原始指针值?如果有人想切题地回答“不要太担心将值传递到嵌套函数”或“我为你提供了完全不同的方法”,那么我也有兴趣听到这一点。
std::shared_ptr存储指向在堆上分配的控制块的指针。毕竟,它必须在该 的所有副本之间共享shared_ptr。因此,当您将 a 应用于const您的时std::shared_ptr,您只是在创建该指针const。所指向的控制块对象仍然是非常量的。思考ControlBlock* const。mutable因此,尽管从逻辑上讲,控制块确实是可变的,但不需要显式关键字。
| 归档时间: |
|
| 查看次数: |
1125 次 |
| 最近记录: |