【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

相关文章
相关标签/搜索