为什么char指针被赋予new [英] Why char pointer is allocated with new

查看:95
本文介绍了为什么char指针被赋予new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了我自己的字符串类,其中我使用char * str

下面是一段代码



从下面代码片段,在param构造函数和复制构造函数中

cstr = str; //这部分语句工作正常。



但是为什么我需要使用new然后strcpy来分配内存?

cstr = new char [strlen(str)+1];

strcpy(cstr,str);


都可以。但为什么选择动态分配方法呢?



我尝试过:



i constructed my own string class where i use char* str
the below is the piece of code

From below code snippet, In param constructor and copy constructor
cstr = str; //this part of statement works fine.

but even then why i need to allocate memory using new and then strcpy required?
cstr = new char[strlen(str) +1];
strcpy(cstr, str);

both works fine. but why to choose dynamic allocation method?

What I have tried:

class CString
{
private:
	char* cstr;
public:
	CString();
	CString(char* str);
	CString(CString& str);
	~CString();

	operator char*();
	//operator const char*();
	CString operator+(const CString& q)const;
	CString operator=(const CString& q);
};
CString::CString()
{
	cout << "constructor" << endl;
	cstr = 0;
}
CString::CString(char *str)
{
	cout << " param constructor" << endl;
	//cstr = str;// this works fine even then we allocating with new why???
	cstr = new char[strlen(str) +1];
	strcpy(cstr, str);
}
CString::CString(CString& q)
{
	cout << " copy constructor" << endl;
	if (this == &q)
		return;
	cstr = q.cstr;
	//cstr = new char[strlen(q.cstr) + 1];
	//strcpy(cstr, q.cstr);
}
CString::~CString()
{
	//if (cstr)
	//	delete[] cstr;
}
CString::operator char*()
{
	cout << " operatorcahr*" << endl;
	return cstr;
}
//CString::operator const char* ()
//{
//	cout << " const operatorcahr*" << endl;
//	return cstr;
//}
CString CString::operator +(const CString &q) const
{
	cout << "operator +*" << endl;
	CString s;
	s.cstr = new char[strlen(cstr) + strlen(q.cstr) + 1];
	strcpy(s.cstr, cstr);
	strcat(s.cstr, q.cstr);
	return s;
}
CString CString::operator =(const CString &q)
{
	cout << "operator =" << endl;
	if (this != &q)
	{
		//if (cstr)
			//delete[] cstr;
		cstr = new char[strlen(q.cstr) + 1];
		strcpy(cstr, q.cstr);
	}
	return *this;
}

int _tmain(int argc, _TCHAR* argv[])
{
	CString a = CString("Hello") + CString(" World");
	cout << a << endl;
	getchar();
	return 0;
}

推荐答案

如果你使用cstr = str;那么你的类只包含一个指向外部初始化字符串的指针,可以在你的类之外进行修改。如果你复制它,你可以完全控制你的类的内部字符串。
If you use cstr = str; then your class just contains a pointer to the external initialisation string, which could be modified outside of your class. If you take a copy of it, you have complete control over your class's internal string.


对于一个字符串,你有一些实际存储它的内存,你有一个指向这个内存的指针引用字符串。如果要创建字符串的副本,则必须复制需要为其分配新内存的内存。



代码中也存在一些错误和可能的优化。



例如,在分配新块时以及销毁对象时应删除旧内存:

With a string you have some memory where it is actually stored and you have a pointer to this memory which references the string. If you want to create a copy of the string you must copy the memory which requires allocating new memory for it.

There are also some errors and possible optimisations in your code.

For example you should delete the old memory when allocating a new block and when the object is destroyed:
CString CString::operator =(const CString &q)
{
    cout << "operator =" << endl;
    if (this != &q)
    {
        // No need to check if cstr is NULL.
        // delete does nothing in this case.
        delete[] cstr;
        // But check here if q.cstr is NULL!
        if (q.cstr)
        {
            cstr = new char[strlen(q.cstr) + 1];
            strcpy(cstr, q.cstr);
        }
        // String is empty now
        else
            cstr = 0;
    }
    return *this;
}







CString::~CString()
{
    delete[] cstr;
}



一旦实现了赋值运算符,它就可以被其他函数使用:


Once you have implemented the assignment operator, it can be used by other functions:

CString::CString(const CString& q)
{
    cout << " copy constructor" << endl;
    *this = q;
}



知道这一点,最好有一个 CString :: CString(const char * s)赋值运算符,因为它可以用于多个复制构造函数。


Knowing this it might be better to have a CString::CString(const char *s) assignment operator instead because that can be used for multiple copy constructors.


这篇关于为什么char指针被赋予new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆