c++ - 此剪辑中共享指针的范围
问题描述
void RecHouse::createRec( const std::string& SourceId,
const std::string& Name,
const std::string& Location,
const std::string& Description,
const std::string& Address,
const std::string& Content,
const std::string& MaxTime,
std::string& RecToken,
bool defRec )
{
std::shared_ptr<Recording> rec = std::make_shared<Recording>(
Recording( SourceId, Name, Location,
Description, Address, Content,
MaxTime, m_EventList,
m_eventServiceResource ));
LOG("finished: create rec object");
m_eventServiceResource->GetEventProducerManager()->RegisterEventProducer( std::weak_ptr<Recording>(recording) );
RecordingToken = recording->getToken();
if ( m_RecordingList.count( RecordingToken ) )
{
throw onvif_exception( BadConfiguration );
}
m_RecordingList[ RecordingToken ] = recording;
updateFindRecordings();
m_serialize.serialize( this );
LOG ("fn end : create rec object");
}
共享指针 rec 的范围是什么?它是否在函数 createRec 结束时完成,因为它没有转移到另一个共享指针?它作为参数发送到 RegisterEventProducer,但仅作为弱指针。这个弱指针进一步存储在弱指针列表中,并且不会被放入共享指针中以供其他地方使用。
解决方案
是的,共享指针超出范围,并且弱指针,正如预期的那样,不会延长生命周期。这是测试它的一种方法:
#include <iostream>
#include <memory>
int main() {
std::weak_ptr<int> weak_rec;
{
std::shared_ptr<int> rec = std::make_shared<int>(200);
weak_rec = rec;
}
std::cout << *weak_rec.lock() << "\n";
return 0;
}
编译并运行 valgrind
#> g++ -g test.cc
#> valgrind ./a.out
输出
==767972== Invalid read of size 4
==767972== at 0x401257: main (test.cc:10)
==767972== Address 0x0 is not stack'd, malloc'd or (recently) free'd
推荐阅读
- vb.net - MSBuild ClickOnce 应用程序:构建后 FTP 上传文件
- .net - NuGet 包在 Azure DevOps Nuget Tool Installer 任务中是否有版本?
- javascript - 如何使用多个查询从 Laravel 中的复选框中获取数据
- c++ - C++ 如何获取二进制文件中的所有行?
- loops - 在 Brainfuck 中,我如何编写一个循环来打印其元素由用户给出的矩阵?
- python - Python 3:是否需要使用 unicode_escape 编码?
- drupal - 为什么我的页面视图在浏览器中显示 500 错误?
- python - 在 Visual Studio Code 中调试 Python 时如何使用“跳转到光标”调试器命令
- c++ - 将 const 类对象传递给 std::function 和 std::bind 导致编译错误
- angularjs - Controller中的Angularjs语言环境