C++11新特性之 Static assertions 和constructor delegation

C++11新特性继续。
Static assertion
static_assert 是在编译时期的断言,作用不言而喻的。
语法是这样:

static_assert ( bool_constexpr , string )   

其中:
bool_constexpr: 常量表达式
string: 如果bool_constexpr表达式为false, 这个string就是编译时候报的错误。

看看代码:

// run-time assert
assert(ptr != NULL)

// C++ 11
// compile-time assert
static_assert(sizeof(void *) == 4, "64-bit is not supported.");

Constructor delegation
之前我们知道,一个类的构造函数不可以调用这个类的其他构造函数。每个构造函数只能包含类的成员变量和共有函数。

// C++03
class A
{
    void init() { std::cout << "init()"; }
    void doSomethingElse() { std::cout << "doSomethingElse()\n"; }
public:
    A() { init(); }
    A(int a) { init(); doSomethingElse(); }
};

但是C++11允许我们这么干!

// C++11
class A
{
    void doSomethingElse() { std::cout << "doSomethingElse()\n"; }
public:
    A() { ... }
    A(int a) : A() { doSomethingElse(); }
};

然后,此时此刻应该有个警告:
wiki :
C++03 considers an object to be constructed when its constructor finishes executing, but C++11 considers an object constructed once any constructor finishes execution. Since multiple constructors will be allowed to execute, this will mean that each delegating constructor will be executing on a fully constructed object of its own type. Derived class constructors will execute after all delegation in their base classes is complete.

For base-class constructors, C++11 allows a class to specify that base class constructors will be inherited. This means that the C++11 compiler will generate code to perform the inheritance, the forwarding of the derived class to the base class. Note that this is an all-or-nothing feature; either all of that base class’s constructors are forwarded or none of them are. Also, note that there are restrictions for multiple inheritance, such that class constructors cannot be inherited from two classes that use constructors with the same signature. Nor can a constructor in the derived class exist that matches a signature in the inherited base class.

Note that in C++03, non-constant data members of classes cannot be initialized at the site of the declaration of those members. They can be initialized only in a constructor. In C++11, now it’s allowed:

// C++11
class A
{
    int a = 99
    void doSomethingElse() { std::cout << "doSomethingElse()\n"; }
public:
    A() { ... }
    A(int a) : A() { doSomethingElse(); }
};

拷贝构造函数使用constructor delegation

A(const A& b) : A() { m_a = b.m_a;
}

你可能感兴趣的:(C++11)