C++11 byte alignment, multi-parametric template, placement new

Source: Internet
Author: User

1. Memory Alignment
#pragmaPack (push, 1)structa{CharA; intb; DoubleC; Chard[ One];};#pragmaPack (POP)#pragmaPack (push, 2)structb{CharA; intb; DoubleC; Chard[ One];};#pragmaPack (POP)voidMain () {cout<<sizeof(A) <<Endl; cout<<sizeof(B) <<Endl;}

The above code demonstrates the use of the #pragma pack () method to implement the memory pair. The next step is to describe how the memory in C++11 is related to it.

1.1 Alignas

ALIGNAS Specifies the size of the memory, and sometimes we want to not align with the default memory alignment, we can use Alignas to specify memory alignment.

In C++11, as long as it is a compile period value (#define, static const, template) are supported Alignas, in addition to note that Alignas can only be changed to small, if you want to small can use the above mentioned #pragma pack (1)

1.2 Alignof and Std::alignment_of

Alignof is used to obtain the memory alignment size, which is simple to use:

A;
cout << alignof (a) << Endl;

Alignof can only return one size_t, and Std::alignment_of inherits from Std::integral_constant, with Value_type,type,value members

cout << std::alignment_of<a>::value << Endl; >>>> 1
cout << std::alignment_of<b>::value << Endl; >>>> 2

1.3 Std::aligned_storage

Std::aligned_storage can be seen as a memory-to-its-buffer, with prototypes as follows:

template<std::size_t Len, std::size_t Align =/*default-alignment*/>

struct aligned_storage;

Len indicates that the sie,align of the stored type represents the memory alignment size of the type

1.4 Max_align_t and Std::align

The std::max_align_t is used to return the maximum default memory alignment type for the current platform, and the alignment and max_align_t types of the memory returned by malloc should be consistent. We can get the maximum default memory alignment for the current platform in the following way:

Std::cout << alignof (std::max_align_t) << Std::endl;

Std::align is used to obtain an address in a large chunk of memory that meets the specified memory requirements

Char " ...... " ; void *ptr =sizeof1; Std::align (alignof (int),sizeof (char), pt,space);
2. Example 2.1. Optional class implementation
//implementing the optional class in boost//This class can store any type of data//int float string struct#pragmaOnceusing namespacestd;template<typename t>classcoptional{ Public:    //Alignof is a version supported in VS2013CTP, if not, use Alignedment_of<t>::value instead//typedef aligned_storage<sizeof (t), alignof (t) >::type Aligendt;    usingAligendt = TypeName aligned_storage<sizeof(T), alignment_of<t>::value>:: type; Coptional () {} coptional (ConstT &t) {Create (t); } coptional (Constcoptional&Other ) {        if(Other.        Isinit ()) {Assign (other); }    }    ~coptional () {if(Isinit ()) {Destroy (); }    }    ConstT &operator*()Const    {        if(Isinit ()) {return* ((T *) (&m_data)); } cout<<"is not init!"<<Endl; }    //create based on parametersTemplate<typename ... Args>voidEmplace (args&& ...        Args) {Destroy (); Create (Forward<ARGS>(Args) ...); }Private: Template<typename ... Args>voidCreate (args&& ... Args) {New(&m_data) T (forward<args> (ARGS) ...);//Placement New CreationM_binit =true; }    //Destroying buffer Objects    voidDestroy () {if(m_binit) {M_binit=false; ((T*) (&m_data))->~T (); }    }    BOOLIsinit ()Const    {        returnM_binit; }    voidAssign (Constcoptional&Other ) {        if(Other.            Isinit ()) {Destroy (); New(&m_data) (T) * ((t*) (&other.m_data)); M_binit=true;    } Destroy (); }Private: Aligendt m_data; BOOLM_binit =false;};
2.2. Lazy Evaluation Class implementation
#pragmaOnce#include<type_traits>#include<boost\optional.hpp>using namespacestd;//implement lazy evaluation class lazyTemplate<typename t>classclazy{ Public: Clazy () {} template<typename Fun, TypeName ... Arg>Clazy ( fun&Fun , ARG ... args) {Std::cout<<"Number of parameters:"<<sizeof... (args) <<Std::endl; M_fun= [&fun, args ...] {returnFun (args ...);}; } T&Value () {if(!m_value.is_initialized ()) {M_value= M_fun ();//Hermit Conversion        }        return*m_value; }    BOOLIscreated ()Const    {        returnm_value.is_initialized (); }Private: Std::function<t () >M_fun; Boost::optional<T>m_value;};
3. Testing
#include"stdio.h"#include"Lazy.h"#include<iostream>using namespacestd; #include"optionalex.h"intFoointx) {cout<<"function Name:"<< __function__ <<Endl; return 2*x;}floatFooadd (intXintYfloatz) {cout<<"function Name:"<< __function__ <<Endl; returnX + y+Z;} Template<typename Fun, TypeName ... Arg>Clazy<typename Result_of<fun (ARG ...) >::type> Lazy (fun && fun, ARG &&.. args) {    returnClazy<typename Result_of<fun (ARG ...) >::type> (forward<fun> (fun), forward<arg>(args) ...);}structtest{intA; floatb; Test (intCanfloatBB): A (AA), B (BB) {} friend Ostream&operator<< (ostream& OS,Consttest&Other ) {OS<< OTHER.A <<" "<< other.b <<Endl; returnOS; }};voidMain () {cout<<"coptional class Test 1, when the object is not initialized:"<<Endl; Coptional<int>OP1; cout<<"Output:"<< *OP1 <<Endl; cout<<"coptional class Test 2,int type:"<<Endl; Coptional<int> OP2 = About; cout<<"Output:"<< *OP2 <<Endl; cout<<"coptional class Test 3,float type:"<<Endl; Coptional<float> OP3 =12.453; cout<<"Output:"<< *OP3 <<Endl; cout<<"coptional class Test 4,struct type:"<<Endl; Coptional<test> OP4 = Test (8,9.8); cout<<"Output:"<< *OP4 <<Endl; cout<<"Lazy class Test:"<<Endl; Clazy<int> Lazy1 (foo,2); cout<< lazy1. Value () <<Endl; Clazy<float> Lazy22 (Fooadd,2,4,6.2); cout<< Lazy22. Value () <<Endl; cout<< lazy ([] (intAintb) {returnA + b; },Ten, A). Value () <<Endl;}

C++11 byte alignment, multi-parametric template, placement new

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.