vector<> inside switch loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
using namespace std;
class tree{
    public :
    int num;
    string code;
    tree* left;
    tree* right;
    tree(int a){
        num = 1;
        code = "";
        left = NULL;
        right = NULL;
    }
};
int main(){
    int mode = 1;
    switch(mode){
    case 1:
        vector<tree> huff;

        break;
    case 2:
        cout << "case 2";
        break;
    }
    return 0;
}


this is my testing code
it gives me the following error message

D:\學區\演算法\test.cpp||In function 'int main()':|
D:\學區\演算法\test.cpp|24|error: jump to case label [-fpermissive]|
D:\學區\演算法\test.cpp|21|error:   crosses initialization of 'std::vector<tree> huff'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|


but if i move "vector<tree> huff;" out of the switch loop
i won't have any error
why is that happening ?
Last edited on
case 1: and case 2: are labels; switch(mode) is an implicit goto to the appropriate label.

The presence of labels and jumps do not change the scope and object life-time rules of the language. vector<tree> object must be destroyed at the end of the switch-case construct (when it goes out of scope).

But a jump to case 2: would bypass the construction ofthe vector<tree> object. Therefore, the program is ill-formed and the compiler emits the diagnostic:
jump to case label crosses initialization of 'std::vector<tree> huff

The error is not specific to vectors in particular, or to objects with non-trivial destructors in general. For an example of the same error involving an int, see: http://www.cplusplus.com/forum/lounge/122363/#msg666967
thank you for answer me the question
but I still have some confusions
1.
do you mean that "vector<tree> huffman" do not have a destructor
if it has one, what is it?
2.
I should never declare object that don't have a destructor in a switch-case scope
> do you mean that "vector<tree> huffman" do not have a destructor

No. It has a non-trivial destructor


> if it has one, what is it?

This: http://en.cppreference.com/w/cpp/container/vector/~vector


> I should never declare object that don't have a destructor in a switch-case scope

If you want to define an object within a switch-case after a case label, do so after introducing a nested block scope.

This is fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
switch(mode) {

    case 1: { // nested block scope

            std::vector<tree> huff; // *** huff: begin life-time

            // ...

    } // *** huff: end life-time

        break;

    case 2:
        std::cout << "case 2";
        break;

    default: { // nested block scope

        int i = 45 ; // *** i: begin life-time

        // ...

    } // *** i: end life-time

}
Topic archived. No new replies allowed.