小编Dou*_*son的帖子

std :: stack会破坏返回值

我已将代码缩减到以下内容以说明我的问题:

#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)

c++ optimization gcc std-pair

4
推荐指数
1
解决办法
232
查看次数

使用dup2,stdout和stderr时出现问题

运行此程序时,"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)

c stdin fork stdout dup2

2
推荐指数
2
解决办法
1万
查看次数

标签 统计

c ×1

c++ ×1

dup2 ×1

fork ×1

gcc ×1

optimization ×1

std-pair ×1

stdin ×1

stdout ×1