小编Doe*_*Doe的帖子

C++ - 在类方法中创建的变量的范围

我正在尝试学习C++,根据我的理解,如果变量超出范围,那么它就会被销毁并重新分配其内存.如果我有一个类并且它的方法创建了一个变量,那么在方法调用之后不应该销毁该变量吗?例如:

class TestClass {
public:
struct Pair{
    std::string name;
    int value;
};
void addPair() {
    //should be deleted after push_back is called?
    Pair x = Pair{ std::string{ "Test Object " }, counter++ };
    pairs.push_back(x);
}
void printPairs() {
    for (int i = 0; i < pairs.size(); i++) {
        std::cout << "pair { " << pairs[i].name << " : " << pairs[i].value << " } " << std::endl;
    }
}
void removePair() {
    pairs.pop_back();
}
private:
    int counter;
    std::vector<Pair> pairs;
}; …
Run Code Online (Sandbox Code Playgroud)

c++ variables methods scope class

4
推荐指数
2
解决办法
144
查看次数

标签 统计

c++ ×1

class ×1

methods ×1

scope ×1

variables ×1