【发布时间】:2010-11-01 18:18:48
【问题描述】:
为了说明我的问题,我已将代码简化为以下内容:
#include <iostream>
#include <stack>
#include <utility>
std::pair<double,double> test(double a, double b)
{
std::stack<int> my_stack;
return std::make_pair<double,double>(a,b);
}
int main()
{
std::pair<double,double> p = test(1.1,2.2);
std::cout << p.first << " " << p.second << "\n";
return 0;
}
当我使用 gcc -O1 标志时,来自 test() 函数的返回值被破坏。这是一些示例输出:
$ gcc -O2 a.cxx -lstdc++
$ ./a.out
1.1 2.2
$ gcc -O1 a.cxx -lstdc++
$ ./a.out
2.60831e-317 2.60657e-317
$ gcc -v
Reading specs from /usr/lib64/gcc-lib/x86_64-suse-linux/3.3.3/specs
Configured with: ../configure --enable-threads=posix --prefix=/usr --with-local- prefix=/usr/local --infodir=/usr/share/info --mandir=/usr/share/man --enable-languages=c,c++,f77,objc,java,ada --disable-checking --libdir=/usr/lib64 --enable-libgcj --with-gxx-include-dir=/usr/include/g++ --with-slibdir=/lib64 --with-system-zlib --enable-shared --enable-__cxa_atexit x86_64-suse-linux Thread model: posix
gcc version 3.3.3 (SuSE Linux)
此代码适用于除“-O1”之外的所有 gcc 优化标志。如果我删除 my_stack 的声明,它也可以工作。您会将其归类为编译器错误,还是我缺少有关 std::stack 和返回 std::pair 值的内容?
【问题讨论】:
-
顺便说一句,
make_pair的全部意义在于不指定模板参数,让它们由函数参数推导。 -
换句话说,你可以简单地写
return std::make_pair(a,b)。由于a和b都是双打,它会正常工作 (tm)
标签: c++ optimization gcc std-pair