Pregunta

Here is a snippet of my code showing a declaration of a vector in a try-catch block:

try {
vector<opClass> op;
}
catch (bad_alloc xa) {
    cout << "\nAllocation failure!\n";
    return 1;
};
//...
//...
op.push_back(<input some stuff>) //error c2065: op undeclared identifier

Strangely when I put my vector declaration outside of the try-catch block, the error goes away. Is this something to do with how vectors are defined in the STL? I thought it would have been good practice to put this declaration in a try-catch block as vectors are dynamic arrays?

¿Fue útil?

Solución

A try block defines a scope. Anything declared inside a scope cannot be used outside that scope. This has nothing to do with vector, it applies to objects of any type. The solution is not to move the declaration outside of the try block, it is to move everything else into the try block.

try {
    vector<opClass> op;
    //...
    //...
    op.push_back(<input some stuff>)
}
catch (bad_alloc xa) {
    cout << "\nAllocation failure!\n";
    return 1;
}

Otros consejos

Scope in a block

A set of curly-brackets { and } is called Compound statement or block (N3242 C++11).

The standard (§3.3.3/1) tells you:

A name declared in a block (6.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (3.3.2) and ends at the end of its block. A variable declared at block scope is a local variable.

This means: Anything declared within a set of curly brackets cannot be accessed outside.

Your variable op is simply not declared after your try-block (which is the case due to the brackets). This is not specific to std::vector but applies to all kinds of variables.

Note also §3.3.3/4:

Names declared in the for-init-statement, the for-range-declaration, and in the condition of if, while, for, and switch statements are local to the if, while, for, or switch statement (including the controlled statement), and shall not be redeclared in a subsequent condition of that statement nor in the outermost block (or, for the if statement, any of the outermost blocks) of the controlled statement; see 6.4.

std::vector

The std::vector is most likely to be implemented with proper try and catch blocks handling the rollback of memory allocation and object construction.

You do not need try/catch stuff when declaring a vector. The vector itself will, nevertheless, not allocate any memory when declared the way you have shown.

vector<opClass> op;

This is an empty vector. There is only space on the stack for this vector and no heap allocation will take place since no memory is required.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top