C++ 表达式

参考:http://zh.cppreference.com/w/cpp/language/expressions

不求值表达式:表达式在编译期被使用,运行期无计算。例如:

#include <iostream>

int foo() noexcept {
    std::cout << "foo called ";
    return 0;
}

int main() 
{
    std::cout << typeid(foo()).name() << std::endl;
    std::cout << sizeof(foo()) << std::endl;
    std::cout << noexcept(foo()) << std::endl;
    std::cout << decltype(foo()){123} << std::endl;
}

但是,typeid有个例:令 typeid(expr), 当expr是广义左值(glvalue)时,expr是对应的运行期计算的(runtime evaluation )。例如:

class Base {
public:
    ~Base() {}
    virtual void foo() {}
};

class Derived : public Base{
public:
    virtual void foo() {}
};

Derived d;

Base& test() {
    std::cout << "test() called \n";
    return d;
}

int main()
{
    std::cout << typeid(test()).name();
    return 0;
}

执行此程序时,会看到cout输出:test() called.  如此行为的动机未明,还需要学习和查阅。

 

posted @ 2018-03-21 11:40  thomas76  阅读(125)  评论(0)    收藏  举报