Programing

C ++에서 "const"는 몇 개나 어떤 것입니까?

crosscheck 2020. 7. 13. 20:34
반응형

C ++에서 "const"는 몇 개나 어떤 것입니까?


초보자 C ++ 프로그래머로서 여전히 나에게 매우 모호한 구조가 const있습니다. 당신은 너무 많은 곳에서 초보자가 살아 나오기에는 거의 불가능한 많은 다른 효과로 그것을 사용할 수 있습니다. 일부 C ++ 전문가는 다양한 용도와 사용 여부 및 / 또는 사용하지 않는 이유를 영원히 설명 할 수 있습니까?


몇 가지 용도를 모 으려고합니다.

수명을 연장하기 위해 일부를 참조에 고정으로 바인딩합니다. 참조는 기본이 될 수 있으며 소멸자는 가상 일 필요는 없습니다. 올바른 소멸자는 여전히 다음과 같이 불립니다.

ScopeGuard const& guard = MakeGuard(&cleanUpFunction);

코드를 사용한 설명 :

struct ScopeGuard { 
    ~ScopeGuard() { } // not virtual
};

template<typename T> struct Derived : ScopeGuard { 
    T t; 
    Derived(T t):t(t) { }
    ~Derived() {
        t(); // call function
    }
};

template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }

이 트릭은 Alexandrescu의 ScopeGuard 유틸리티 클래스에서 사용됩니다. 임시가 범위를 벗어나면 Derived의 소멸자가 올바르게 호출됩니다. 위의 코드는 작은 세부 사항을 그리워하지만 큰 문제입니다.


const를 사용하여 다른 메소드가이 오브젝트의 논리적 상태를 변경하지 않도록하십시오.

struct SmartPtr {
    int getCopies() const { return mCopiesMade; }
};

copy-on-write 클래스에 const를 사용 하여 컴파일러 가 복사 할시기와 시기를 결정할 수 있도록합니다.

struct MyString {
    char * getData() { /* copy: caller might write */ return mData; }
    char const* getData() const { return mData; }
};

설명 : 원본과 copie'd 객체의 데이터가 동일하게 유지되는 한 무언가를 복사 할 때 데이터를 공유 할 수 있습니다. 개체 중 하나가 데이터를 변경하면 이제 원본과 복사본의 두 가지 버전이 필요합니다. 즉,이다 복사 A의 쓰기 그들은 지금 모두 자신의 버전이 너무 어느 객체.

코드 사용 :

int main() {
    string const a = "1234";
    string const b = a;
    // outputs the same address for COW strings
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}

The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write std::string. Both strings, even though they are distinct objects, share the same memory for their string data. Making b non-const will prefer the non-const version of the operator[] and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of a!

int main() {
    string const a = "1234";
    string b = a;
    // outputs different addresses!
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}

For the copy-constructor to make copies from const objects and temporaries:

struct MyClass {
    MyClass(MyClass const& that) { /* make copy of that */ }
};

For making constants that trivially can't change

double const PI = 3.1415;

For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing

void PrintIt(Object const& obj) {
    // ...
}

There are really 2 main uses of const in C++.

Const values

If a value is in the form of a variable, member, or parameter that will not (or should not) be altered during its lifetime you should mark it const. This helps prevent mutations on the object. For instance, in the following function I do not need to change the Student instance passed so I mark it const.

void PrintStudent(const Student& student) {
  cout << student.GetName();
}

As to why you would do this. It's much easier to reason about an algorithm if you know that the underlying data cannot change. "const" helps, but does not guarantee this will be achieved.

Obviously, printing data to cout does not require much thought :)

Marking a member method as const

In the previous example I marked Student as const. But how did C++ know that calling the GetName() method on student would not mutate the object? The answer is that the method was marked as const.

class Student {
  public:
    string GetName() const { ... }
};

Marking a method "const" does 2 things. Primarily it tells C++ that this method will not mutate my object. The second thing is that all member variables will now be treated as if they were marked as const. This helps but does not prevent you from modifying the instance of your class.

This is an extremely simple example but hopefully it will help answer your questions.


Take care to understand the difference between these 4 declarations:

The following 2 declarations are identical semantically. You can change where ccp1 and ccp2 point, but you can't change the thing they're pointing at.

const char* ccp1;
char const* ccp2;

Next, the pointer is const, so to be meaningful it must be initialised to point to something. You can't make it point to something else, however the thing it points to can be changed.

char* const cpc = &something_possibly_not_const;

Finally, we combine the two - so the thing being pointed at cannot be modified, and the pointer cannot point to anywhere else.

const char* const ccpc = &const_obj;

The clockwise spiral rule can help untangle a declaration http://c-faq.com/decl/spiral.anderson.html


As a little note, as I read here, it's useful to notice that

const applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right).

참고URL : https://stackoverflow.com/questions/455518/how-many-and-which-are-the-uses-of-const-in-c

반응형