strcpy()在Visual Studio 2012中的行为

时间:2014-09-01 22:54:55

标签: c++ visual-studio-2012

作为我老师的一项任务,我们被告知要写一个简单的课程。在我写的构造函数内部(C ++ Visual Studio 2012):

void CCar::CCar(char* model){
    if(this->model!=NULL) delete[] this->model;
    this->model= new char[strlen(model)+1];
    strcpy(this->model, model);
}

我被告知我的代码是错误的,因为我使用new动态分配了内存,而且我不应该strcpy分配内存,所以我所写的是不好的做法。如果没有进一步<string.h>指定安全功能,我已经被告知要包含#define,您能否指出我在strcpy的行为被彻底指定的参考?我的代码吗?

1 个答案:

答案 0 :(得分:4)

strcpy不分配任何内存。

在C标准中,功能按以下方式描述

  

strcpy函数复制s2指向的字符串(包括   将空字符终止)到s1指向的数组中。如果   复制发生在重叠的对象之间,行为是   未定义。返回3 strcpy函数返回s1的值。

其中s1和s2是函数参数。

构造函数可能看起来像

#include <cstring>

//...

CCar::CCar( const char* model )
{
    this->model = new char[std::strlen( model )+1];
    std::strcpy( this->model, model );
}

或者您可以使用标准班std::string。那就是数据成员模型必须定义为类型std::string

在这种情况下,构造函数看起来像

#include <string>

//...

CCar::CCar( const char* model ) : model( model )
{
}

顺便说一下构造函数中的这个语句是错误的

if(this->model!=NULL) delete[] this->model;

它可能导致未定义的行为,因为对于没有静态存储持续时间的类的本地对象,数据成员模型可以具有任意值。因此,尝试删除未分配的内存,但模型mignt不等于NULL。