在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?

请每个回答只回答一个特征。


当前回答

这不是一个奇怪的功能,事实上,如果你仔细想想,它是完全有意义的,但还是给了我一个WTF时刻。

在c++(和c#)中,基类的子类不能访问基实例上的私有和受保护成员。

class Base {
protected:
 m_fooBar;
};

class Derived: public Base {
public:
 void Test(Base& baseInstance) {
  m_fooBar=1; //OK
  baseInstance.m_fooBar = 1; //Badness
  //This, however is OK:
  ((Derived&)baseInstance).m_fooBar = 1; //OK
 }
};

其他回答

有趣的自动装箱和Java中的整数缓存:

Integer foo = 1000;
Integer bar = 1000;

foo <= bar; // true
foo >= bar; // true
foo == bar; // false

//However, if the values of foo and bar are between 127 and -128 (inclusive)
//the behaviour changes:

Integer foo = 42;
Integer bar = 42;

foo <= bar; // true
foo >= bar; // true
foo == bar; // true

解释

快速浏览一下Java源代码将会出现以下内容:

/**
 * Returns a <tt>Integer</tt> instance representing the specified
 * <tt>int</tt> value.
 * If a new <tt>Integer</tt> instance is not required, this method
 * should generally be used in preference to the constructor
 * {@link #Integer(int)}, as this method is likely to yield
 * significantly better space and time performance by caching
 * frequently requested values.
 *
 * @param  i an <code>int</code> value.
 * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    if (i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

注意:IntegerCache。High默认为127,除非由属性设置。

自动装箱的情况是,foo和bar都是从缓存中检索到相同的整数对象,除非显式创建:例如,foo = new integer(42),因此在比较引用是否相等时,它们将为真而不是假。比较Integer值的正确方法是使用.equals;

Duff的C语言设备!

在C语言中,可以将do/while语句与switch语句交错使用。下面是memcpy使用此方法的示例:

void duff_memcpy( char* to, char* from, size_t count ) {
    size_t n = (count+7)/8;
    switch( count%8 ) {
    case 0: do{ *to++ = *from++;
    case 7:     *to++ = *from++;
    case 6:     *to++ = *from++;
    case 5:     *to++ = *from++;
    case 4:     *to++ = *from++;
    case 3:     *to++ = *from++;
    case 2:     *to++ = *from++;
    case 1:     *to++ = *from++;
            }while(--n>0);
    }
}

对我来说,它绝对是INTERCAL中的PLEASE修饰符。 如果PLEASE出现的次数不够多,则认为程序不够礼貌,错误消息如下所示;如果太频繁,这个程序可能会被认为过于礼貌而被拒绝。

在c#中: A = cond ?B: c; 如果“b”和“c”是“赋值不兼容”,你永远不会得到结果,即使“a”是对象。 它是ms中最常用和最愚蠢的实现运算符。有关比较,请参阅D语言中的实现(关于类型推断的注意)。

C + + 1 xλ的:

[] (int x) { std::cout << x << std::endl; } ();

它们可能被滥用在一些奇怪的语法中:

[](){}();[]{[]{}();}();

这是完全有效的c++ 1x。