【C++】 3_C++11 新特性

using 關鍵字

  • using 主要使用情形
using-directive for namespace and using-declarations for namespace members

(名稱空間使用指令和名稱空間成員使用聲明)node

using namespace std;

using std::count;
using-declarations for class members

(類成員的使用聲明)ide

<stl_bvector.h>

protected:
    using _Base::M_allocate;
    using _Base::M_deallocate;
    using _Base::_S_nword;
    using _Base::M_get_Bit_allocator;

<std_list.h>
    using _Base::_M_impl;
    using _Base::_M_put_node;
    using _Base::_M_get_node;
    using _Base::_M_get_Tp_allocator;
    using _Base::_M_get_Node_allocator;

noexcept 關鍵字

void foo() noexcpet; 

==>

void foo() noexcept(true);
declares that foo() won't throw. If an exception is not handled local inside foo() —— thus, if foo() throws —— the program is terminated, calling std::terminate(), which by default calls std::abort().

( 聲明foo()不會拋出。 若是沒有在foo()內局部處理異常 —— 那麼若是foo()拋出 —— 程序終止,調用std :: terminate(),默認狀況下調用std :: abort()。)函數


You can even specify a condition under a function throws no exception. For example, for any type Type, the global swap() usually is defined as follows:

(甚至能夠在函數不引起異常的狀況下指定條件。 例如,對於任何類型Type,一般將全局swap() 定義以下:)this

void swap(Type &x, Type &y) noexcept(noexcept(x.swap(y)))
{
    x.swap(y);
}
Here, inside noexception (...), you can specify a Boolean condition under which no exception gets thrown: Specifying noexcept without noexception is a short form of specifying noexcept(true).

(在這裏,在no exception(…)中,能夠指定一個布爾條件,在該條件下不會引起異常:指定noexcept而不指定noexception是指定noexcept(true)的縮寫形式。)spa


You need to inform C++(specifically std::vector) that your move constructor and destructor does not throw. Then the move construct will be called when the vector grows. If the construtor is not noexcept , std::vector can't use it, since then it can't ensure the expction guarantes demanded by the standard.

(你須要通知C ++(特別是std :: vector)你的move構造函數和析構函數不會拋出。 而後,當向量增加(擴容)時,將調用move構造函數。 若是構造函數不是noexcept,則std :: vector不能使用它,由於那樣就不能確保標準要求的保護性保證。)code

class MyString
{
private:
    char *_data;
    size_t _len;

    // ...

public:
    // move construct
    MyString(MyString &&str) noexcept : _data(str._data), _len(str._len)
    { }

    // move assignment
    MyString &operator=(MyString &&str) noexcept
    {
        // ...
        return *this;
    }
};
  • 注: growable conatiner (會發生 memory reallocation) 只有兩種:vector 和 deque

vector:
1_meitu_1.jpgorm

deque:
2.jpgblog

相關文章
相關標籤/搜索