Nice programing

C ++ 자동 및 자동

nicepro 2021. 1. 6. 20:49
반응형

C ++ 자동 및 자동


지역 변수를 만들 때 (const) auto&또는 사용하는 것이 맞 auto습니까?

예 :

SomeClass object;
const auto result = object.SomeMethod();

또는 const auto& result = object.SomeMethod();

SomeMethod ()는 원시 값이 아닌 값을 반환합니다. 다른 사용자 정의 유형일 수도 있습니다. 내 이해는 const auto& resultSomeMethod ()에 의해 반환 된 결과가 반환 된 형식에 대한 복사 생성자를 호출하기 때문에 정확합니다. 내가 틀렸다면 나를 바로 잡으십시오.

원시 유형은 어떻습니까? 나는 const auto sum = 1 + 2;옳다고 생각한다 .

범위 기반 for 루프에도 적용됩니까?

for(const auto& object : objects)

auto그리고 auto &&대부분의 경우를 포함합니다 :

  • auto로컬 사본이 필요할 때 사용하십시오 . 이것은 참조를 생성하지 않습니다. 복사 (또는 이동) 생성자가 있어야하지만 복사 제거 최적화 로 인해 호출되지 않을 수 있습니다 .

  • auto &&객체가 로컬인지 아닌지 상관하지 않을 때 사용 합니다. 기술적으로 이것은 항상 참조를 생성하지만 이니셜 라이저가 일시적인 경우 (예 : 함수가 값으로 반환 됨) 기본적으로 로컬 객체처럼 동작합니다.

    또한 auto &&개체가 수정 가능하다는 보장도 없습니다. const객체 또는 참조가 주어지면 const. 그러나 특정 컨텍스트를 고려할 때 수정 가능성이 종종 가정됩니다.

auto &그리고 auto const &좀 더 구체적인 :

  • auto &변수를 다른 것과 공유하고 있음을 보장합니다. 항상 참조이며 일시적인 것이 아닙니다.

  • auto const &과 유사 auto &&하지만 읽기 전용 액세스를 제공합니다.

원시 / 비 원시 유형은 어떻습니까?

다른 점이 없다.

범위 기반 for 루프에도 적용됩니까?

예. 위의 원칙을 적용하여

  • auto &&루프 내에서 시퀀스 값을 수정하고 버리는 기능에 사용 합니다. (즉, 컨테이너가과 같은 읽기 전용보기를 제공하지 않는 한, std::initializer_list이 경우 사실상 auto const &.)
  • auto &의미있는 방식으로 시퀀스 값을 수정하는 데 사용 합니다.
  • auto const &읽기 전용 액세스에 사용 합니다.
  • auto(수정 가능한) 사본 작업에 사용 합니다.

당신은 또한 auto const참조없이 언급합니다. 이것은 작동하지만 이미 소유 한 항목에 대한 읽기 전용 액세스의 이점이 거의 없기 때문에 일반적으로 사용되지 않습니다.


예, 그것은 사용하여 정확 auto하고 auto&지역 변수. 함수의 반환 유형을 가져올 때를 사용하는 것도 정확합니다 auto&. 이는 범위 기반 for 루프에도 적용됩니다.

사용 auto대한 일반적인 규칙 은 다음과 같습니다.

  • auto x사본으로 작업 할시기를 선택하십시오 .
  • auto &x원본 항목으로 작업 할시기를 선택 하고 수정할 수 있습니다.
  • 선택 auto const &x당신이 원래 항목을 작업 할하고이를 수정하지 않습니다 때.

여기 에서 자동 지정자에 대해 자세히 읽을 수 있습니다 .


auto템플릿과 같은 형태 추론의 동일한 메커니즘, 내가 그 추론하는 중괄호 초기화하기 목록의 존재의 알고있는 유일한 예외 사용 auto등을 std::initializer_list하지만, 템플릿 맥락에서 비 추론.

auto x = expression;

먼저 오른쪽 표현식의 유형에서 모든 참조 및 cv 한정자를 제거한 다음 유형을 일치시키는 방식으로 작동합니다. 예를 들어, 당신이있는 경우 const int& f(){...}다음 auto x = f();추론 x으로 int, 그리고 없습니다 const int& .

다른 형태는

auto& x = expression

제거하지 않고 , 위의 예를 사용하여, 따라서, CV-한정자 auto& x = f()추론을 x같이 const int&. 다른 조합은 cv 한정자를 추가합니다.

유형이 항상 cv-ref 한정자로 추론되도록 decltype(auto)하려면 decltype유형 추론 규칙 을 사용하는 C ++ 14에서 악명 높은 것을 사용하십시오 .

따라서 간단히 말해서 사본을 원하면을 사용 auto하고 참조를 원하면 auto&. const추가 const-ness 를 원할 때마다 사용하십시오 .


편집 추가 사용 사례가 있습니다.

auto&& x = expression;

which uses the reference-collapsing rules, same as in the case of forwarding references in template code. If expression is a lvalue, then x is a lvalue reference with the cv-qualifiers of expression. If expression is a rvalue, then x is a rvalue reference.


When creating local variables, is it correct to use (const) auto& or auto?

Yes. The auto is nothing more than a compiler-deduced type, so use references where you would normally use references, and local (automatic) copies where you would normally use local copies. Whether or not to use a reference is independent of type deduction.

Where SomeMethod() returns a non-primitive value - maybe another user-defined type. My understanding is that const auto& result is correct since the result returned by SomeMethod() would call the copy constructor for the returned type. Please correct me if I am wrong.

Legal? Yes, with the const. Best practice? Probably not, no. At least, not with C++11. Especially not, if the value returned from SomeMethod() is already a temporary. You'll want to learn about C++11 move semantics, copy elision, and return value optimization: https://juanchopanzacpp.wordpress.com/2014/05/11/want-speed-dont-always-pass-by-value/

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=199

https://isocpp.org/wiki/faq/ctors#return-by-value-optimization

What about for primitive types? I assume const auto sum = 1 + 2; is correct.

Yes, this is fine.

Does this also apply to range based for loops?

for(const auto& object : objects)

Yes, this is also fine. I write this sort of code at work all the time.

ReferenceURL : https://stackoverflow.com/questions/29859796/c-auto-vs-auto

반응형