gpt4 book ai didi

c++ - 为什么此 C++ 代码会在 ideone.com 上出现 SIGILL?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:10 28 4
gpt4 key购买 nike

为什么会这样?该代码适用于 Linux 上的 GCC 4.7 和 Windows 上的 MSVC++ 2010,并且不会生成警告。然而,在 ideone.com 上它 crashes使用 SIGILL。这里是否涉及未定义的行为?

#include <iostream>
#include <cstdarg>

using namespace std;

enum types
{
INT,
DOUBLE,
CHAR,
STRING
};

struct mt
{
types type;

union
{
int i;
double d;
char c;
const char *s;
} val;

mt(int i)
: type(INT)
{
val.i = i;
}

mt(double d)
: type(DOUBLE)
{
val.d = d;
}

mt(char c)
: type(CHAR)
{
val.c = c;
}

mt(const char *s)
: type(STRING)
{
val.s = s;
}
};

void print(int n, ...)
{
va_list ap;

va_start(ap, n);

for (int i = 0; i < n; i++)
{
mt x(va_arg(ap, mt));

switch (x.type)
{
case INT:
cout << x.val.i << endl;
break;
case DOUBLE:
cout << x.val.d << endl;
break;
case CHAR:
cout << x.val.c << endl;
break;
case STRING:
cout << x.val.s << endl;
break;
}
}

va_end(ap);
}

int main()
{
print(4, mt(2), mt(4.2), mt('a'), mt("Hello"));
}

最佳答案

我在 GCC 4.4.6 中遇到错误:

test.cpp: In function ‘void print(int, ...)’:
test.cpp:59: warning: cannot receive objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp: In function ‘int main()’:
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
test.cpp:83: warning: cannot pass objects of non-POD type ‘struct mt’ through ‘...’; call will abort at runtime
$ g++ --version
g++ (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3)

您不能通过可变参数函数参数传递 struct,而是传递指针:

void print(int n, ...)
{
va_list ap;

va_start(ap, n);

for (int i = 0; i < n; i++)
{
mt *x(va_arg(ap, mt *));

switch (x->type)
{
case INT:
cout << x->val.i << endl;
break;
case DOUBLE:
cout << x->val.d << endl;
break;
case CHAR:
cout << x->val.c << endl;
break;
case STRING:
cout << x->val.s << endl;
break;
}
}

va_end(ap);
}

int main()
{
mt mt1(2);
mt mt2(4.2);
mt mt3('a');
mt mt4("Hello");
print(4, &mt1, &mt2, &mt3, &mt4);
}

这在我的系统上运行良好:

$ ./a.out
2
4.2
a
Hello

关于c++ - 为什么此 C++ 代码会在 ideone.com 上出现 SIGILL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326459/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com