1

why error happend, I think const auto data_0 should be the same with const Data* data_1, what's the difference bwtween data_0 and data_1?

class Data { public: Data(int val_) : val(val_) { } ~Data() { } void SetVal(int val_) { val = val_; } private: int val; }; Data* GetData(int val) { return new Data(val); } int main () { const auto data_0 = GetData(0); const Data* data_1 = GetData(0); data_0->SetVal(1); // OK data_1->SetVal(1); // error: passing ‘const Data’ as ‘this’ argument discards qualifiers return 0; } 
1
  • 1
    Hint: data_0's type is Data* const data_0;. Commented Oct 28, 2020 at 4:28

2 Answers 2

3

const applies to the thing on its left, unless there is nothing then it applies to the thing on its right.

In const auto data_0 = GetData(0);, the const applies to whatever type auto deduces to, which in this case is Data*. So, the final declaration is:

Data * const data_0 = GetData(0);

The const applies to the pointer itself, not the thing it is pointing at. Thus, data_0 is a const pointer to a non-const Data object. SetVal() is a non-const method, so it can be called on the object.

In const Data* data_1 = GetData(0);, the const applies to Data. So, the final declaration is:

Data const * data_1 = GetData(0);

The const applies to the thing being pointed at, not to the pointer itself. Thus, data_1 is a non-const pointer to a const Data object. SetVal() is not a const method, so it cannot be called on the object.

Sign up to request clarification or add additional context in comments.

Comments

1

what's difference between const auto and const type*

const auto will be deduced from the initialiser and will be a const qualified type. In case of data_0, the type of the initialiser is a pointer to non-const Data and therefore the deduced type becomes a const qualified pointer to non-const Data i.e. Data* const.

const type* is a non-const qualified pointer to a const qualified object of type type. The difference is that one is non-const pointer to const and the other is const pointer to non-const.

why error happend

Because you call a non-const qualified member function through a pointer to const.

I think const auto data_0 should be the same with const Data* data_1

It isn't, and it shouldn't be.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.