添加 std::vector 声明会产生奇怪的行为吗?

问题描述 投票:0回答:1

我在以下程序中遇到了奇怪且不一致的行为:

注意:下面的程序可能具有未定义的行为,并且可能会产生破坏性影响。根据您自己的判断和风险运行它

这是一个结构

struct MyStruct {
    int* myarr;
    int size;

    MyStruct(int size) {
        myarr = new int[size];
        for (int i = 0; i < size; i++) {
            myarr[i] = i;
        }
    }

    
    
    MyStruct(const MyStruct& other) {
        size = other.size;
        myarr = new int[size];
        for (int i = 0; i < size; i++) {
            myarr[i] = other.myarr[i];
        }
    }
    

   
    MyStruct(MyStruct&& other) {
        this->myarr = other.myarr;
        this->size = other.size;

        other.myarr = nullptr;
    }

    
    MyStruct& operator=(MyStruct&& other) {
        this->myarr = other.myarr;
        this->size = other.size;

        other.myarr = nullptr;
        return *this;
    }
    
};

功能:

MyStruct newStruct(MyStruct& temp, int size) { 
    temp = MyStruct{size};
    return temp;
}

主要功能:

int main() {
    vector<int> myvector {1};
    
    MyStruct tempStruct {2};
    MyStruct myst {newStruct(tempStruct, 5)};
}

当我编译此代码并运行它时,输出是:

terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length

或者它会无限期地运行,过了一段时间我必须用 SIGKILL 终止该进程,否则系统会给我: ''文件系统根剩余空间少于 X'

问题是,当我删除看似不相关的向量声明或主函数中除向量声明之外的所有内容时,问题就解决了,并且输出完全符合预期。

用其他类型(例如 std::string )替换向量声明会产生相同的行为。

发生什么事了?

c++ c++11
1个回答
0
投票

正如注释中正确指出的,构造函数 MyStruct(int size) 不会初始化成员变量 MyStruct::size,从而导致未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.