小编Mor*_*ang的帖子

当C++将元素从函数的返回值存储到std :: vector时出现意外的结果

当函数涉及重新分配时,我发现一些编译器可能在函数调用之前保存地址.它导致存储在无效地址中的返回值.

在上面的描述中有一个例子来解释行为.

#include <stdio.h>
#include <vector> 
using namespace std;

vector<int> A; 
int func() { 
    A.push_back(3);
    A.push_back(4);
    return 5; 
} 
int main() { 
    A.reserve(2);
    A.push_back(0);
    A.push_back(1);
    A[1] = func();
    printf("%d\n", A[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有一些常见的C++编译器,测试结果如下.

  • GCC(GNU编译器集合):运行时错误或输出 1
  • Clang:输出 5
  • VC++:输出 5

是不确定的行为?

c++ gcc vector compiler-optimization compiler-bug

45
推荐指数
1
解决办法
1866
查看次数

标签 统计

c++ ×1

compiler-bug ×1

compiler-optimization ×1

gcc ×1

vector ×1