declaring a const instance of a class

后端 未结 4 788
面向向阳花
面向向阳花 2020-12-08 19:11

Let\'s say I have a class defined as follows:

class foo{};

now, this is perfectly acceptable;

foo f;

how

相关标签:
4条回答
  • 2020-12-08 19:49

    Your class is a POD (essentially because it doesn’t provide a default constructor). POD variables are not initialized upon declaration. That is, this:

    foo x;
    

    does not initialize x to a meaningful value. This has to be done separately. Now, when you declare it as const, this may never happen because you cannot assign to or change x any more.

    Consider the equivalence to int:

    int x; // legal
    const int y; // illegal
    

    As you have noticed, using std::string instead of foo compiles. That’s because std::string is not a POD. A simple solution to your dilemma is to provide a default constructor for foo:

    class foo {
    public:
        foo() { }
    };
    

    Now your const foo x; code compiles.

    0 讨论(0)
  • 2020-12-08 19:49

    Raising an error in the situation of an empty class is a known problem, and reported as issue #253.

    0 讨论(0)
  • 2020-12-08 19:50

    I think there are more alternatives. You can do

    const foo f={};
    

    or

    const foo f(());
    

    Const means you can not assign to it later, so you have to initialize it. Since you did not define default constructor the compiler assumes it has to be initialized by you. std::string has default constructor so it is called implicitly by compiler.

    0 讨论(0)
  • 2020-12-08 20:02

    const, applied to a simple plain-old-data variable, indicates that that variable will not change in that context - so you aren't going to be able to reassign it to something. Therefore, you must initialize it or it will be perpetually uninitialized and thus useless.

    0 讨论(0)
提交回复
热议问题