简体   繁体   中英

what's difference between const auto and const type*

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;
}

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.

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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM