简体   繁体   English

当该类具有const char *构造函数时,为什么用const char *变量构造该类的未分配临时实例,为什么会出错?

[英]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?

Why does this code (unassigned temporary variable constructed from a const char* variable): 为什么使用此代码(由const char *变量构造的未分配临时变量):

class A
{
public:
    A(const char*) {}
};

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

Give these errors? 给这些错误?

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

Whereas this code (assigned temporary variable constructed from a const char* variable): 而此代码(从const char *变量构造的分配临时变量):

class A
{
public:
    A(const char*) {}
};

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

Gives no errors. 没有错误。

And this code (unassigned temporary variable constructed from a const char* variable static_cast to a const char*): 以及以下代码(从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;
}

Gives no errors. 没有错误。

Bonus points if you can provide the section number in the C++ specification that specifies the first code sample to be not allowed. 如果可以在C ++规范中提供部分编号以指定不允许的第一个代码示例,则可以加分。

A(constCharPointerVariable);

This is actually a declaration of a variable of type A named constCharPointerVariable . 这实际上是A名为constCharPointerVariable的类型A变量的声明。 It does not create a temporary object. 它不会创建临时对象。

If you used clang, you'd get the more helpful error message: 如果您使用clang,则会收到更有用的错误消息:

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

As a simpler example, the following is invalid because it declares two int objects in the same scope, both named x : 作为一个更简单的示例,以下内容无效,因为它在同一作用域中声明了两个名为x int对象:

int x(0);
int (x);

As for why the code is parsed this way, you can find the syntax rules for Declarators in §A.7 of C++11. 至于为什么用这种方式解析代码,可以在C ++ 11的§A.7中找到声明符的语法规则。 Basically, when you declare a variable, you can enclose its name in any number of parentheses. 基本上,声明变量时,可以将其名称括在任意数量的括号中。

Relevant productions include: 相关作品包括:

  • declarator -> ptr-declarator 声明 -> ptr-declarator
  • ptr-declarator -> noptr-declarator | ptr声明器 -> noptr声明器 | declarator-id 声明者编号
  • noptr-declarator -> ( ptr-declarator ) noptr-declarator -> ( ptr-declarator )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM