为什么C ++没有const构造函数?

为什么C ++没有const构造函数?

问题描述:

编辑:重大变化,因为上一个示例有缺陷,这可能使一些答案/评论看起来很奇怪)

过度设计,但以下是合法的,因为缺乏const构造函数:

This might be an overly contrived, but the following is legal because of lack of const constructor:

    class Cheater
    {
    public:
        Cheater(int avalue) 
           : cheaterPtr(this) //conceptually odd legality in const Cheater ctor
           , value(avalue) 
        {}

        Cheater& getCheaterPtr() const {return *cheaterPtr;}
        int value;

    private:
        Cheater * cheaterPtr;
    };

    int main()
    {
        const Cheater cheater(7); //Initialize the value to 7

        cheater.value                 = 4;    //good, illegal
        cheater.getCheaterPtr().value = 4;    //oops, legal

        return 0;
    }

看起来像提供一个const构造函数,方法,类似于一个const重载。

It seems like providing a const constructor a thing would be as easy technically as const methods, and be analogous to a const overload.

注意:我不是在寻找' Image(const Data& data )const ',而是' const Image(const Data& data)const '

所以:


  • 为什么C ++中没有const构造函数?

以下是一些与上下文相关的资料:

Here's some related material for context:

  • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm
  • How to deal with initialization of non-const reference member in const object?
  • C++, Classes, Const, and strange syntax


它不会是一个const方法本身

It would not be a const method itself

如果这个构造函数不是一个 const 方法本身,那么内部指针等也不会 const 。因此,它不能将 const 值设置为那些非 - const 成员。

If this constructor were not a const method itself, then the internal pointers and such would also not be const. Therefore, it could not set const values into those non-const members.

使它在句法上工作的唯一方法是,这个构造函数需要所有非 - mutable 成员的成员初始化。基本上,任何未声明 mutable 的成员在使用此构造函数时将隐式声明为 const 。这相当于使构造函数 const 方法;只有初始化器可以初始化成员。构造函数的身体对于不可变成员不能做任何事情,因为那时这些成员将是 const

The only way to make it work syntactically is for this constructor to require member initialization for all non-mutable members. Essentially, any member not declared mutable would be implicitly declared const when using this constructor. Which is equivalent to making the constructor a const method; only initializers could initialize members. The constructor's body could do nothing with non-mutable members, because those members would be const at that point.

你要求的是句法上可疑的。你基本上试图欺骗API,将常量数据存储在一个为可变数据设计的对象中(这就是为什么你没有将成员指针声明为 const )。如果你想要一个对象有不同的行为,你需要声明对象具有那个特定的行为。

What you are asking for is syntactically dubious. You're essentially trying to hoodwink the API, storing constant data in an object that is designed for mutable data (which is why you didn't declare the member pointer to be const). If you want different behavior for an object, you need to declare the object to have that specific behavior.