Are temporary objects in C++ const indeed?

前端 未结 6 1790
走了就别回头了
走了就别回头了 2021-01-06 10:11

I always believed that temporary objects in C++ are automatically considered as const by the compiler. But recently I experienced that the following example of code:

6条回答
  •  滥情空心
    2021-01-06 10:53

    Temporary objects can be const, but they don't have to be.

    ((string const)"hello").append(" world"); // error!
    

    It allows for various things. Consider

    struct bitref {
      int index;
      bitref &operator=(bool value); // non-const!
    };
    
    struct bitset {
      int flags;
      // returns a bitref temporary that's associated with the bit
      // at index 'index'. 
      bitref operator[](int index); 
      // ...
    };
    

    You could do

    bitset b;
    b[1] = true; // change second bit to 1
    

    This is what's done by the std::bitset<> template.

提交回复
热议问题