为什么用const char*变量构造类的未分配临时实例是错误的,而该类具有const char*constructor

Why is it an error to construct an unassigned temporary instance of a class with a const char* variable when that class has a const char* constructor?

本文关键字:char const 错误 constructor 实例 分配 变量 为什么      更新时间:2023-10-16

为什么这个代码(由const char*变量构建的未分配临时变量):

class A
{
public:
    A(const char*) {}
};
int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A(constCharPointerVariable);
    return 0;
}

给出这些错误?

error C2512: 'A' : no appropriate default constructor available
error C2040: 'constCharPointerVariable' : 'A' differs in levels of indirection from 'const char *'

而这段代码(由常量字符*变量构造的临时变量):

class A
{
public:
    A(const char*) {}
};
int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A a(constCharPointerVariable);
    return 0;
}

没有错误。

这段代码(未分配的临时变量由const char*变量static_cast构造为const char*)

class A
{
public:
    A(const char*) {}
};
int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A(static_cast<const char*>(constCharPointerVariable));
    return 0;
}

没有错误。

如果您可以在C++规范中提供指定不允许使用的第一个代码示例的节号,则可以获得额外的分数。

A(constCharPointerVariable);

这实际上是一个名为constCharPointerVariableA类型变量的声明。它不会创建临时对象。

如果你使用clang,你会得到更有用的错误消息:

error: redefinition of 'constCharPointerVariable' with a different type
    A(constCharPointerVariable);
      ^

作为一个更简单的示例,以下内容是无效的,因为它声明了同一范围中的两个int对象,均命名为x:

int x(0);
int (x);

至于为什么以这种方式解析代码,您可以在中找到Declarator的语法规则C++11的§A.7。基本上,当您声明一个变量时,您可以将其名称括在任意数量的括号中。

相关产品包括:

  • 声明符->ptr声明符
  • ptr声明符->noptr声明器|声明符id
  • noptr声明符->(ptr声明器)