Amusing C++:运算符顺序和类的构造函数

本文通过几个有趣的C++代码片段,展示了C++中一些容易被误解的语言特性,包括运算符的优先级、构造函数调用规则等,提醒开发者注意这些陷阱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文网址   http://www.codeguru.com/cpp/article.php/c19303/Amusing-C.htm

Q.: How many apples does Bart have?

A.: Who knows? We're still unaware of how many apples he had to start!

Can C++ be funny? Let's check it out! Here are some examples that gladden the programmer's eye. Enjoy looking at them!

Let us start - and may the Source be with you! Suppose we have the following code:

int a = 5;
int b = a++ + ++a;

What does b equal? Are you sure? :) The point is that the right value lies somewhere between 10 and 14! My GCC returns 12, but that's not the limit yet! The C++ Standard does not presuppose the calculation of the ++ operator before the assignment operator is done - so that the answer may vary depending on the compiler; it may even depend on the optimization keys. Note that the result of the operation i = i++ is not defined either! People who want to learn more, can google "C++ sequence point", while we go on!

What do you think - is this code workable?

int i[i];
int j = j;
x x;
int y::y = x.x;

Strange as it may seem, it is - if we do like this:


const int i = 1;
const int j = 2;
struct x
{
   int x;
};
namespace y
{
   int i[i];
   int j = j;
   x x;
   int y::y = x.x;
};

Visibility overlap did its dirty deed! :) However, MSVC does not accept such code: it considers the declaration of int x to be a declaration of the constructor (the latter, as is known, cannot return a value). And, what's even worse, the namespaced variable j will have an unexpected value, though it is "initialized". So, this clearly indicates that such "tricks" are not worth being played!

Let's go on with the next example. Here's another nice code I've gotten you into! :) This one marked the beginning of my collection of C++ pranks, and I like it the most. Apart from being a really cool prank, it also comprises a psychological trick. Just look at this:

T t1;
T t2(t1);
T t3 = t1;
T t4();

Which constructor will be called in each of these four cases? If you have decided that those must be:

  • default constructor,
  • copy constructor,
  • assignment operator, and
  • default constructor again,
then you are mistaken... twice! Of course, first comes the default constructor; second comes the copy one, which apparently follows from the syntax. But in the third case, in spite of the = sign, ye good olde copy constructor is activated; we create a new object, not initialize an existing one! The last case is not the creation of an object at all, it's... the declaration of a function! The latter does not take the parameters and returns the type T; compare:

int func();

If you made no mistakes, congratulations! If you made one nevertheless and are now craving another chance to win, here's a new opportunity for you! Suppose you have this class:

class C {
public:
    C()                    { printf("default\n"); }
    C(long)                { printf("long\n"); }
    explicit C(int)        { printf("int\n"); }
    C(const C&)            { printf("copy\n"); }
    C &operator=(const C&) { printf("op=\n"); return *this; }
};
Also, you have a code that involves it:

void prn(int n)
{
   cout << n << ": ";
}
int main()
{
   const int i = 0;
   prn(1); C c1();
   prn(2); C c2 = i;
   prn(3); C c3(i);
   prn(4); C c4 = C(i);
   prn(5); C c5 = (C) i;
   prn(6); C c6 = static_cast(i);
   return 0;
}
What will be displayed on the screen then? To be honest, I made a mistake myself here. And that mistake was severe and reiterated :) So, please be extremely focused. Done? The right answer is:

1: 2: long
3: int
4: int
5: int
6: int 
Naturally, one is blank; as you remember, it is a function declaration. Two did not manage to build a class from int, since the int-constructor is specified as explicit; however, the compiler obligingly converted int into long - where its own constructor already exists. The rest of options are variations on a theme of C(i), although differently decorated. I cannot but admire the competence of the translator, which used neither excessive copy constructor, nor assignment constructor, nor even default constructor. C++ at its best!

Here's the last example - maybe the most "practical" among those cited. Suppose you need to create a cycle in which the value of a variable tends to zero. Certainly, you can use the operator for. But we can also do like this!

int i = 10;
while (i --> 0)
{
   cout << i << endl;
}

This thingamajig is called "arrow operator", just in case.

Here were the tricks originating in our more-than-native language. And then, C++0x may well come, which conceals many such pranks, I guess. As for now, let's keep in mind that this code is nothing but a joke - it ain't a blueprint for action! :)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值