我应该声明任何可以是const const方法的方法

Sam*_*rsa 6 c++ const-correctness

简单的问题.Should I declare any method that can be const a const method?这包括不返回任何成员变量的方法,或返回对成员变量的const引用.有没有理由不这样做(除了显而易见的原因,编译器会指出这些原因)?

Ale*_*ler 13

const无法通过指向常量对象的指针调用非方法.所以,如果方法可能const,不声明为const会强加其使用人为限制.

除此之外,制作方法const是一种重要的语义细节,可以让用户感受到调用它所带来的效果.

  • 还要注意物理常数和逻辑常量之间的(重要)差异.所以这篇文章有更多细节:http://drdobbs.com/cpp/184403892. (4认同)

Dav*_*eas 6

我似乎在这里作为记录说明:

我应该声明任何可以是const const方法的方法吗?

不,在设计过程中,应该在不同的层面上做出决定.您应该标记为语义上不修改对象的const所有方法.这可能包括一些实际修改某些内部细节的方法,这些内部细节不是对象的可感知状态的一部分(这些属性应该是),并且它可能不包括一些根本不改变任何东西的方法.mutable

enum impl {                 // different implementations of the algorithm
   one_implementation,
   another_implementation
};
class example {
   mutable std::pair<bool, int> cache;
protected:
   int a, b;
public:
   example( int a, int b ) : cache(), a(a), b(b) {}
   virtual ~example() {}
   void set( int _a, int _b ) { 
      cache.first = false;      // invalidate previous result 
      a = _a;
      b= _b;
   }
   int expensive_calculation() const {
      if ( !cache.first ) {
         cache.second = calculate();
         cache.first = true;
      }
      return cache.second;
   }
   virtual void change_impl( impl x ) {}
private:
   virtual int calculate() const = 0;
};
Run Code Online (Sandbox Code Playgroud)

在它的当前形式中,你不能改变实现,并且change_impl是非const的,即使它没有修改它没有标记为的任何成员属性const,因为从语义上它确实改变了.

另一方面,该expensive_calculation()方法不会在语义上修改对象的状态,在调用操作之前和之后可感知状态将是相同的,但它确实修改了cache属性以加速以后的调用(如果状态没有改变) ).因此,该方法是const,并且缓存是mutable.


And*_*sen 5

是.根据Effective C++,"尽可能使用const".