开发者

const qualifier for a string literal

开发者 https://www.devze.com 2023-02-12 06:33 出处:网络
I have the following code which I wrote to test the const member function: It compiles and runs fine when I have the const qualifier for the data member

I have the following code which I wrote to test the const member function: It compiles and runs fine when I have the const qualifier for the data member char *data and to the argument for the constructor. However if I remove const from the data member and the constructor, i get compiler error. Is it because the string "Hello Wo开发者_如何学Gorld" is always of type const char * ?

#include <iostream>
#include <string.h>

using namespace std;

class mystring {
        const char *data;
        mutable int length;
        mutable int valid;
public:
        mystring(const char *str) {data = str;}
        ~mystring() { };
        int GetLength() const;
};

int mystring::GetLength() const
{
        if (valid)
                return length;
        else {
                length = strlen(data);
                valid = 1;
                return length;
        }
}

int main()
{
        const char *str = "Hello World";

        mystring s(str);

        cout << s.GetLength() << endl;
}


If you remove the const from the constructor, it is telling callers that it expects to take a char* as a parameter and might change the char at the end of the pointer.

Because you are constructing mystring with a const char*, the compiler is raising an error to help ensure your code does what it expects to do.


You are trying to construct a mystring with a const char* when it wants a char* as its parameter. You cannot go from const to non const without a cast.


Yes, string literals in C++ are of type const char *.

To treat it as char *, you need to do const_cast<char*>(str). This is probably a bad idea though - modifying a string literal results in undefined behaviour.


If you remove const from the constructor parameter and from the data member, the code will not compile because the argument str you are passing to your constructor is declared as const char *. It has absolutely nothing to do with "Hello World" literal at all. You can initialize your str with 0 instead of "Hello World", and the code will still fail to compile.

String literal "Hello World" has type const char[12]. However , language rules allow converting string literals to char * type, which means that if you initialized your object as

mystring s("Hello World");

the code would compile fine even after you removed const from the constructor parameter and from the data member. But once you throw that intermediate variable str into the picture "Hello World" becomes irrelevant. It doesn't matter anymore what "Hello World" is. Only what str is matters.

0

精彩评论

暂无评论...
验证码 换一张
取 消