我已将代码缩减到以下内容以说明我的问题:
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我使用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 …Run Code Online (Sandbox Code Playgroud) 运行此程序时,"stdr"行显示在"stdout"行之前.为什么?我认为dup2会使stderr和stdout使用相同的文件描述符,所以缓冲应该没有问题.我在Solaris 10上使用gcc 3.4.6.
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd[2];
int pid;
char buf[256];
int n;
if(pipe(fd) < 0) {
perror("pipe");
return 1;
}
if((pid = fork()) < 0) {
perror("fork");
return 1;
}
else if(pid > 0) { // parent
close(fd[1]);
if((n = read(fd[0], buf, sizeof(buf))) > 0) {
buf[n] = 0;
printf("%s", buf);
}
}
else {
dup2(fd[1], fileno(stdout));
dup2(fd[1], fileno(stderr));
close(fd[1]);
fprintf(stdout,"stdout\n");
fprintf(stderr,"stderr\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)