Dynamically allocate memory to a char-pointer [closed]

守給你的承諾、 提交于 2019-12-25 02:46:22

问题


Is this correct code or should I dynamically allocate memory to the member-variable of the String-class that receives the char-pointer?

#include <iostream>
using namespace std;

class String {
    char *string;
public:
    String(char *ch) {
    string = ch;
}

void print() {
    cout << string;
}

};

int main() {

   String string("hello");
   string.print();

return 0;

}


回答1:


Let start from statement

String string("hello");

Here "hello" is a string literal. Used as an argument it is implicitly converted to an object of type

const char *

So the corresponding data member of the class should be defined as

const char *string;

And as the result the class should be defined as

class String 
{
private:
    const char *string;
public:
    String( const char *ch ) : string( ch )
    {
    }

    void print() const 
    {
        cout << string;
    }
};

As string literals have static storage duration then your code is valid. Take into account that the class does not possess the pointer.

On the other hand if you want that the class indeed possesses the pointer then you need dynamically allocate a copy of the data pointed to by the constructor argument. In this case you need also explicitly define at least the copy constructor, copy assignment operator, and destructor.



来源:https://stackoverflow.com/questions/23441919/dynamically-allocate-memory-to-a-char-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!