当你只复制指针而不是整个数据时,它仍然是一个复制构造函数吗?

is it still a copy constructor when you only copy the pointer instead of the entire data?

假设我有一个名为 classname 的 class,这个 class 有 char* 私有数据成员。

在我正在学习的 class 中,教授希望我们像下面的那样做,本质上是创建一个全新的数组。

classname(const classname & source)
{
         c_string = new char[strlen(source.c_string)+1];

         strcpy(c_string, source.c_string);

}

但是如果这两个对象本质上共享同一个数组(已经创建),就像这个一样。

classname(const classname & source)
{
         c_string = source.c_string;
}

我知道这不一定会做任何事情 'copying' 并且拥有不同的指针(属于不同的对象)可能会有风险。但它被认为是复制构造函数吗?还是为了使其成为复制构造函数,还必须创建第二个数组?

根据我一直在阅读的内容,我觉得第二个是这种情况,但我需要一个明确的 NO THAT'S NOT A COPY CONSTRUCTOR 来完全克服这个问题。 谢谢你。

正如评论者都正确指出的那样,无论函数的内容如何,​​您所拥有的一个复制构造函数。

这是一个复制构造函数,因为标准是这样说的 (see 12.8.2):

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (...).

因为您有一个 classname 的非模板构造函数,其签名与 const classname& 相匹配,所以您有一个复制构造函数。也许不是一个很好的复制构造函数,也许是一个甚至不复制的损坏的复制构造函数,但仍然是一个复制构造函数。

既然我说的比不上评论的人,那我就简单引用一下吧:

Copy constructor is defined by its signature, not the content in the function body.-

You are doing a shallow copy rather than a deep copy but it's still a copy-constructor.-