Pergunta

Give the example:

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 );
} 

Does it 'survives' for a call to Display? (Not that this is what I mean by 'long-life term')

Because the pointer is deallocated at the next bracket. I know a vector storing pointers such as std::vector<A*>vecHold, vecHold.push_back( ptr ) would be illegal, but what about in this case?

Foi útil?

Solução

vecHold.push_back( *ptr ); 

Creates a copy of the object pointed by ptr(ret) and then adds it in to the vector vecHold. ret is a local static object which remains valid and has the lifetime same as the lifetime of your program. So vecHold holds a valid object and there is nothing incorrect w.r.t in the program.

Outras dicas

When a variable is declared as static inside a function, it means that its lifetime will last the whole time of the program. So in this case it's safe to return and store pointers or references to it.

Your code creates a copy of the vector. Vectors are not automatically passed by reference (nor is anything else I can think of). If you want a reference then write the code to use one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top