[英]C++ | Method scope pointer management
I got a question about pointers: 我有一个关于指针的问题:
class CAppFramework : public IBaseApp
{
public:
CAppFramework( std::initializer_list< CClientApp* > input );
CAppFramework( );
~CAppFramework( );
void Create( ) override;
void Release( ) override;
template< class T > T** Request( std::string c_appname )
{
for ( auto c_app : m_ClientApps )
{
if ( c_app -> GetName( ) == c_appname )
{
T** t_app = reinterpret_cast< T** >( c_app );
return t_app;
}
}
return nullptr;
}
std::vector< CClientApp* >& GetClientApps( );
private:
std::vector< CClientApp* > m_ClientApps;
};
void CTest::Create( )
{
std::cout << "Ayye" << std::endl;
CTest* test = *( m_Framework->Request< CTest >(
"Test" ) );
test -> RunTest( );
}
CTest is a derived class from CClientApp. CTest是CClientApp的派生类。
Do I need to delete test? 我需要删除测试吗? Cause if I do, I get an access violation.
如果我这样做,我会收到访问冲突。 I suppose that is because "Request" is returning a pointer to a pointer that is inside a vector, so when I dereference it and delete it, it would delete the object in the vector which will / might still get used?
我想那是因为“Request”正在返回一个指向一个向量内部的指针的指针,所以当我取消引用它并删除它时,它会删除向量中的对象,它仍然会被使用?
This is more of a general question. 这是一个普遍的问题。 Do I need to delete every pointer or just pointers that are dynamically allocated using "new"?
我是否需要删除每个指针或仅使用“new”动态分配的指针?
I hope someone can help me. 我希望有一个人可以帮助我。
You obviously don't need to delete every pointer, otherwise you would have to write code like this: 您显然不需要删除每个指针,否则您必须编写如下代码:
int main( int argc, char ** argv ) {
// stuff
delete argv;
}
If you explicitly create something with new
and assign the pointer new gives you to a raw pointer, then you need to delete
that pointer. 如果使用
new
显式创建并指定new指针,则会指向原始指针,然后需要delete
该指针。 Of course, this is error prone, and can't be made exception-safe, and so you should be using things like std::unique_ptr and std::make_unique instead. 当然,这容易出错,并且不能使其异常安全,因此您应该使用std :: unique_ptr和std :: make_unique之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.