프로그래밍/C++

C++ 11 항목

이재만박사 2020. 11. 19. 15:53

auto


변수의 자료형을 컴파일 시간에 자동으로 추론


선언시 추론된 형은 종료시까지 사용됨


대입시 자료현 변경이 안 됨


auto a = 10;   // int


auto b = 1.0f;  // float


auto c = 1.0;   // double


auto d = "abc"; // char* 


auto e = {1, 2, 3}; // std::initializer_list


auto f = { 10 }; // c++ 14까지는 std::initializer_list, c++17 부터는 int


auto g { 10 }; // int


g = 12.34;   // warning C4244: '=' 데이터 손실


string h = { "abc" };


auto i = h.begin( ); // std::string::iterator

    

    

vector<int> v = {1,2,3,4,5};

//auto 키워드를 사용한 전 vector를 순회하는 반복자의 선언

for (intVector::iterator it = v.begin(); it != v.end(); ++it) {

    cout << *it << endl;

}


//auto 키워드를 사용한 후 vector를 순회하는 반복자 선언

for (auto it = v.begin(); it != v.end(); ++it) {

    cout << *it << endl;

}


//auto 키워드를 이용한 for loop 

for (auto& value : v) {

    cout << value << endl;

}




value category ( 값 유형 )


값의 분류 기준


값이 식별성을 갖고 있는가?


값이 메모리에서 이동할 수 있는가?


(gl-value, pr-value, x-value, l-value, r-value)


       값 유형              값이 메모리에서 이동      값이 메모리에서 이동 X



값이 식별성을 가질 때      x - value                   l - value           gl-value



값이 식별성이 없을 때      pr-value

   (임시 변수)


                                r-value




int && c = 10;


r-value를 참조하는 연산자



decltype


현재 변수나 표현식의 타입을 알아낼 수 있는 명령어


int a = 10;


decltype(a) b = 2; // int b = 2;


int& x = a;


decltype(x) c = b; // int& c = b;



const int i = 4;


auto j = i;  // int j = i;


decltype(i) k = i;  // const int k = i;




int arr1[10];


auto arr2 = arr1; // int* arr2 = arr1;


decltype(arr1) arr3 = arr1; // int arr3[10] 으로 선언








decltype 키워드


템플릿 함수에서 어떤 객체의 타입이 템플릿 인자들에 의해서 결정되는 경우



template <typename T, typename U>


void add(T t, U u, decltype(t + u)* result) {

   

    *result = t + u;


}


template <typename T, typename U>


auto add(T t, U u) -> decltype(t + u) {

  return t + u;

}







vector의 emplace_back( )과 push_back( )의 차이



push_back( ) 메서드


 - 일반적으로 '객체' 삽입


 - 객체가 없이 삽입하려면 임시 객체(rvalue) 가 있어야 함


 - 암시적 형 변환이 가능하다면 인자로도 삽입 


 - 이는 인자를 통해 임시객체를 암시적으로 생성한 후 삽입




std::vector<myString> vecString;


myString str = "hello1";


vecString.push_back(str); // str 객체 소멸


vecString.push_back(myString("hello2")); // 임시 객체 소멸


vecString.push_back("hello3"); // 임시 객체 소멸


vecString.push_back(std::move(myString("hello4")); // 해제 안 됨



대입에 관한 이동 연산자


myString& operator=(myString&& right);