using-declaration typedef別名 - 在C++11中'typedef'和'using'有什麼區別?




using用法 class (5)

它們基本上是相同的,但using提供alias templates非常有用。 我能找到一個很好的例子如下:

namespace std {
 template<typename T> using add_const_t = typename add_const<T>::type;
}

所以,我們可以使用std::add_const_t<T>來代替typename std::add_const<T>::type

我知道在C ++ 11中,我們現在可以using用於寫入類型別名,如typedef s:

typedef int MyInt;

據我所知,相當於:

using MyInt = int;

這種新的語法來源於努力去表達“ template typedef ”:

template< class T > using MyType = AnotherType< T, MyAllocatorType >;

但是,對於前兩個非模板示例,標準中是否還有其他細微差別? 例如, typedef以“弱”方式進行別名。 也就是說,它不會創建新的類型,而只是一個新的名稱(這些名稱之間的轉換是隱含的)。

它是否與using相同或是否會生成新類型? 有什麼區別嗎?


它們相當於標準(重點是我的)(7.1.3.2):

typedef名稱也可以通過別名聲明引入。 using關鍵字後面的標識符變為typedef-name,標識符後面的可選attribute-specifier-seq屬於該typedef-name。 它具有與typedef說明符所引入的相同的語義。 特別是它沒有定義一個新的類型,它不會出現在type-id中。


除此之外,它們在很大程度上是相同的

The alias declaration is compatible with templates, whereas the C style typedef is not.


使用語法在模板中使用時具有優勢。 如果您需要類型抽象,但還需要保留模板參數以便將來可以指定。 你應該寫這樣的東西。

template <typename T> struct whatever {};

template <typename T> struct rebind
{
  typedef whatever<T> type; // to make it possible to substitue the whatever in future.
};

rebind<int>::type variable;

template <typename U> struct bar { typename rebind<U>::type _var_member; }

但是使用語法簡化了這個用例。

template <typename T> using my_type = whatever<T>;

my_type<int> variable;
template <typename U> struct baz { my_type<U> _var_member; }

You know what a copy semantics means right? it means you have types which are copyable, for user-defined types you define this either buy explicitly writing a copy constructor & assignment operator or the compiler generates them implicitly. This will do a copy.

Move semantics is basically a user-defined type with constructor that takes an r-value reference (new type of reference using && (yes two ampersands)) which is non-const, this is called a move constructor, same goes for assignment operator. So what does a move constructor do, well instead of copying memory from it's source argument it 'moves' memory from the source to the destination.

When would you want to do that? well std::vector is an example, say you created a temporary std::vector and you return it from a function say:

std::vector<foo> get_foos();

You're going to have overhead from the copy constructor when the function returns, if (and it will in C++0x) std::vector has a move constructor instead of copying it can just set it's pointers and 'move' dynamically allocated memory to the new instance. It's kind of like transfer-of-ownership semantics with std::auto_ptr.







c++ c++11 typedef using-declaration