我一直认为,临时对象会一直存在到完整表达式的末尾。然而,std::vector 和数组的初始化之间有一个奇怪的区别。
请考虑以下代码:
#include <iostream>
#include <vector>
struct ID{
static int cnt;
// the number of living object of class ID at the moment of creation:
int id;
ID():id(++cnt){}
~ID(){
cnt--;
}
};
int ID::cnt=0;
int main(){
int arr[]{ID().id, ID().id};
std::vector<int> vec{ID().id, ID().id};
std::cout<<" Array: "<<arr[0]<<", "<<arr[1]<<"\n";
std::cout<<" Vector: "<<vec[0]<<", "<<vec[1]<<"\n";
}
这个程序的输出有点(至少对我来说)出乎意料:
Array: 1, 1
Vector: 1, 2
这意味着,临时对象在 std::vector 的整个初始化过程中是事件的,但在数组的情况下它们是一个接一个地创建和销毁的。我希望临时人员能够生存到完整表达式 int arr[]{ID().id, ID().id}; 完成。
该标准提到了一个关于临时对象的生命周期和数组初始化的异常(exception) (12.2)。但是我不明白它的含义,也不知道为什么在这种特殊情况下应用它:
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.
使用不同编译器的结果概述(MSVS 结果是 NathanOliver 的屈从):
Array Vector
clang 3.8 1, 2 1, 2
g++ 6.1 1, 1 1, 2
icpc 16 1, 1 1, 2
MSVS 2015 1, 1 1, 2
正如 ecatmur 所指出的,对于聚合初始化,braced-init-list 的每个元素都是一个完整表达式,因此以下代码
struct S{
int a;
int b;
} s{ID().id, ID().id};
std::cout<<" Struct: "<<s.a<<", "<<s.b<<"\n";
应该将 Struct 1, 1 打印到控制台。这正是 g++ 编译的程序所做的。但是,clang 似乎有一个错误 - 生成的程序打印 Struct 1, 2。
已向 clang 报告了一个错误:https://llvm.org/bugs/show_bug.cgi?id=29080
最佳答案
这是core issue 1343 "Sequencing of non-class initialization" , 于 2016 年 11 月被论文 P0570R0 接受为缺陷报告.提议的决议是 C++17 的一部分,但因此不是 C++14 的一部分,因此(除非委员会决定发布 C++14 的更正)这是 C++17 和 C+ 之间的区别点+14。
根据C++14标准的规则,正确的输出是数组1, 1和 vector 1, 2;这是因为构造 vector (包括从braced-init-list)需要调用构造函数,而构造数组则不需要。
控制这一点的语言在 [intro.execution] 中:
10 - A full-expression is an expression that is not a subexpression of another expression. [...] If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. [...]
这作为一个顶级概述很好,但它留下了一些未回答的问题:
数组是一个聚合,因此根据[dcl.init.aggr]从一个braced-init-list初始化;这表示每个元素直接从列表的对应元素初始化,因此没有隐式函数调用(至少不对应于整体初始化)。在语法级别,在 initializer ([dcl.init]/1) 中使用 braced-init-list 作为 大括号或相等初始化器,完整表达式是包含在大括号内并用逗号分隔的表达式。在每个完整表达式结束时,临时对象的析构函数都需要运行,因为 [class.temporary] 中提到的三个上下文都不是这里的情况。
vector 初始化的情况不同,因为您使用的是 initializer_list 构造函数,因此会发生函数的隐式调用(即 initializer_list 构造函数) ;这意味着在整个初始化过程中存在一个隐式的完整表达式,因此只有在 vector 的初始化完成时才会销毁临时对象。
令人困惑的是,[dcl.init.list] 说您的代码“大致相当于”:
const int __a[2] = {int{ID().id}, int{ID().id}}; // #1
std::vector<int> vec(std::initializer_list<int>(__a, __a + 2));
但是,这必须在上下文中读取 - 例如,支持 initializer_list 的数组的生命周期受 vector 初始化的限制。
这在 C++03 中要清楚得多,在 [intro.execution] 中有:
13 - [Note: certain contexts in C++ cause the evaluation of a full-expression that results from a syntactic construct other than expression (5.18). For example, in 8.5 one syntax for initializer is
( expression-list )but the resulting construct is a function call upon a constructor function with expression-list as an argument list; such a function call is a full-expression. For example, in 8.5, another syntax for initializer is= initializer-clausebut again the resulting construct might be a function call upon a constructor function with one assignment-expression as an argument; again, the function call is a full-expression. ]
这一段是从 C++11 中完整删除的;这是根据 CWG 392 的决议.由此产生的困惑可能不是故意的。
在 P0570R0 之后,[intro.execution] 声明 full-expression 是:[...]
- an init-declarator ([dcl.decl]) [...] including the constituent expressions of the initializer, or [...]
- an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression.
所以在 C++17 中,完整的表达式是 arr[]{ID().id, ID().id} 和 vec{ID().id, ID().id} 分别正确的输出是 1, 2 在每种情况下,因为第一个临时 ID 的销毁推迟到完整表达式的结尾。
关于c++ - 列表初始化期间临时对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025342/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser