代码之家  ›  专栏  ›  技术社区  ›  Thomas Matthews

C++容器与C语言结构的混合

c++
  •  0
  • Thomas Matthews  · 技术社区  · 6 年前

    我花了2天时间来追查一个涉及C++容器的问题, std::list 标准::列表 参数)?

    #include <list>
    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    struct Point_Struct
    {
      int x;
      int y;
    };
    
    typedef struct Point_Struct Point;
    
    int main()
    {
      std::list<Point> line;
      Point p;
      p.x = 3;
      p.y = 10;
      line.push_back(p);
    
      cout << "Size of container: " << line.size() << "\n";
    
      //  Here's the issue:
      line.pop_back();
    
      //  The size should be zero.
      cout << "Size of container after pop_back(): " << line.size() << "\n";
    
      return 0;
    }
    

    pop_back .

    对于任何更改 list ,例如分配和 sort .

    如果我改变 line std::list<Point_Struct>

    注意:这个问题是在一个更大的程序中发现的。上面的代码说明了问题的根本原因: std::list<typedef struct> 与。 std::list<struct>

    注意:异常是在VS2017调试模式下抛出的,但不是在发布模式下。

    抱歉,下面有多个问题:

    1. 是否存在标准C++(11或更高版本)中声明未定义的任何内容 使用 typedef struct 作为模板 参数 标准::列表

    2. 这会是一个Visual Studio错误吗?

    我没有试过使用G++或其他编译器。

    编辑1:VS2017版本信息
    Microsoft Visual Studio专业版2017
    版本15.9.14
    安装产品:Visual C++ 2017—-03696000—00—1—AA071

    编译信息
    配置:调试
    平台:Win32


    启用C++异常:是(/ EHsc)
    基本运行时检查:两者(/RTC1)
    禁用语言扩展:否

    站台

    1 回复  |  直到 6 年前
        1
  •  -1
  •   Alexandre Senges    6 年前

    我在Eclipse(Ubuntu 18)中用g++11编译并运行了你的代码,它运行得很好,

    输出:

    Size of container: 1
    Size of container after pop_back(): 0
    

    你试过交换吗 typedef using ? 这可能会解决问题:

    #include <list>
    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    struct Point_Struct
    {
      int x;
      int y;
    };
    
    using Point = Point_Struct;
    
    int main()
    {
      std::list<Point> line;
      Point p;
      p.x = 3;
      p.y = 10;
      line.push_back(p);
    
      cout << "Size of container: " << line.size() << "\n";
    
      //  Here's the issue:
      line.pop_back();
    
      //  The size should be zero.
      cout << "Size of container after pop_back(): " << line.size() << "\n";
    
      return 0;
    }