举个例子:
class A
{
public:
int value;
A():value(1){};
~A(){};
};
void Display( std::vector<A> myvector )
{
for( std::vector<A>::iterator it = myvector.begin(); it!= myvector.end(); ++it )
std::cout << (*it).value << std::endl;
}
A* GetAtId( DWORD id )
{
if( id != 0 )
{
static A ret;
return& ret;
}
return NULL;
}
void Serialize( DWORD obj[3] )
{
std::vector<A> vecHold;
for( int i=0; i<3; i++ )
{
A* ptr = NULL;
if( obj[i] != 0 )
{
ptr = GetAtId( obj[i] );
if( ptr ) vecHold.push_back( *ptr );
}
}
Display( vecHold );
}
int main( )
{
DWORD id[3] = {0,};
id[2] = 9;
Serialize( id );
}
它是否“幸存”以调用 to Display
?(并不是这就是我所说的“长期”的意思)
因为指针在下一个括号处被释放。我知道存储诸如std::vector<A*>vecHold
,之类的指针的向量vecHold.push_back( ptr )
是非法的,但是在这种情况下呢?