草庐IT

c++ - 显式构造函数和嵌套初始化列表

coder 2023-11-14 原文

下面的代码可以用大多数现代 C++11 兼容编译器(GCC >= 5.x、Clang、ICC、MSVC)成功编译。

#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1({{{"test"}}});
}

但是为什么首先要编译它,列出的编译器如何解释该代码?

为什么 MSVC 能够在没有 B(B &) = delete; 的情况下编译这个,但是其他3个编译器都需要吗?

以及为什么当我删除 时它在除 MSVC 之外的所有编译器中都失败不同的签名复制构造函数,例如B(const B &) = delete; ?

编译器甚至都选择相同的构造函数吗?

为什么 Clang 会发出以下警告?
17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1({{{"test"}}});

最佳答案

我将尝试解释标准所说的内容,而不是解释编译器的行为。

主要示例

直接初始化 b1来自 {{{"test"}}} ,重载决议适用于选择B的最佳构造函数.因为没有来自 {{{"test"}}} 的隐式转换至 B& (列表初始值设定项不是左值),构造函数 B(B&)不可行。然后我们关注构造函数 B(A) ,并检查它是否可行。

{{{"test"}}} 确定隐式转换序列至 A (为了简单起见,我将使用符号 {{{"test"}}} -> A),重载决议适用于选择 A 的最佳构造函数,所以我们需要比较 {{"test"}} -> const char*{{"test"}} -> std::string (注意最外层的括号被省略)根据 [over.match.list]/1 :

When objects of non-aggregate class type T are list-initialized such that [dcl.init.list] specifies that overload resolution is performed according to the rules in this subclause, overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T...

  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

... In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.



请注意,无论说明符 explicit 是什么,这里都会考虑所有构造函数。 .
{{"test"}} -> const char*根据 [over.ics.list]/10 不存在和 [over.ics.list]/11 :

Otherwise, if the parameter type is not a class:

  • if the initializer list has one element that is not itself an initializer list...

  • if the initializer list has no elements...

In all cases other than those enumerated above, no conversion is possible.



确定{{"test"}} -> std::string ,同样的过程,重载决议选择std::string的构造函数接受类型为 const char* 的参数.

结果,{{{"test"}}} -> A通过选择构造函数来完成 A(std::string) .

变化

如果explicit怎么办已移除?

过程不会改变。 GCC 会选择构造函数 A(const char*)而 Clang 将选择构造函数 A(std::string) .我认为这是 GCC 的一个错误。

如果b1的初始化器中只有两层大括号怎么办? ?

备注 {{"test"}} -> const char*不存在但 {"test"} -> const char*存在。所以如果b1的初始化器中只有两层大括号, 构造函数 A(const char*)被选中是因为 {"test"} -> const char*优于{"test"} -> std::string .结果,在复制列表初始化中选择了显式构造函数(构造函数 A 中的参数 B(A) 来自 {"test"} 的初始化),然后程序是非良构的。

如果构造函数 B(const B&) 呢?被宣布?

请注意,如果声明 B(B&),也会发生这种情况。已移除。这次我们需要比较{{{"test"}}} -> A{{{"test"}}} -> const B& , 或 {{{"test"}}} -> const B相当于。

确定{{{"test"}}} -> const B ,采用上述过程。我们需要比较{{"test"}} -> A{{"test"}} -> const B& .备注 {{"test"}} -> const B&根据 [over.best.ics]/4 不存在:

However, if the target is

— the first parameter of a constructor or

— the implicit object parameter of a user-defined conversion function

and the constructor or user-defined conversion function is a candidate by

— [over.match.ctor], when the argument is the temporary in the second step of a class copy-initialization,

— [over.match.copy], [over.match.conv], or [over.match.ref] (in all cases), or

the second phase of [over.match.list] when the initializer list has exactly one element that is itself an initializer list, and the target is the first parameter of a constructor of class X, and the conversion is to X or reference to cv X,

user-defined conversion sequences are not considered.



确定{{"test"}} -> A ,再次进行上述过程。这与我们在上一小节中讨论的案例几乎相同。结果,构造函数A(const char*)被选中。注意这里选择构造函数来确定{{{"test"}}} -> const B ,实际上并不适用。尽管构造函数是显式的,但这是允许的。

结果,{{{"test"}}} -> const B通过选择构造函数来完成 B(A) ,然后是构造函数 A(const char*) .现在都{{{"test"}}} -> A{{{"test"}}} -> const B是用户定义的转换序列,两者都不优于另一个,所以b1的初始化是模棱两可的。

如果括号被大括号代替怎么办?

根据 [over.best.ics]/4 ,在上一小节中被块引用,用户定义的转换 {{{"test"}}} -> const B&不考虑。因此即使构造函数 B(const B&) 结果与主要示例相同被宣布。

关于c++ - 显式构造函数和嵌套初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47534938/

有关c++ - 显式构造函数和嵌套初始化列表的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  3. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  4. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  5. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  6. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  9. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  10. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

随机推荐