此剪辑中共享指针的范围
Scope of shared pointer in this clippet
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
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