当我检查以下程序及其输出时,我发现通过返回值获取 FrameA 对象非常困惑:
让编译器生成ctor时,成员数组字段初始化为全0
auto a = f(); // f() --> return A();
给出以下SSCCE
#include <cstring>
#include <iostream>
#include <chrono>
#include <algorithm>
using namespace std;
const int MAX = 9999999;
struct FrameA {
// FrameA() {}
// FrameA(const FrameA &v) { memcpy(data, v.data, sizeof(data)); }
char data[1000];
};
FrameA f(int i) { return FrameA(); }
int test(int odd) {
int sum = 0;
auto begin = chrono::steady_clock::now();
for (int i = 0; i < MAX; ++i) {
auto v = f(odd);
sum += v.data[0] + v.data[330];
}
auto end = chrono::steady_clock::now();
cout << chrono::duration_cast<chrono::milliseconds>(end - begin).count()
<< " (milliseconds)" << endl;
return sum;
}
int _tmain(int argc, _TCHAR *argv[]) {
test(0);
test(1);
return 0;
}
当定义一个空构造函数时,输出如下:
g++ v4.8.1
72 (milliseconds)
73 (milliseconds)
但是使用编译器生成的ctor,输出是:
g++ v4.8.1
1401 (milliseconds)
1403 (milliseconds)
我也在VC12上测试过,结果差不多。
检查程序集后,我发现使用编译器生成的ctor时:
for (int i = 0; i < MAX; ++i) {
auto v = f(odd);
00A31701 push 3E8h
00A31706 lea eax,[ebp-3F8h]
00A3170C push 0
00A3170E push eax
00A3170F call _memset (0A32460h) ;; memset FrameA to 0
sum += v.data[0] + v.data[330];
00A31714 movsx eax,byte ptr [ebp-3F8h]
但使用空构造函数不会调用 memset 将 FrameA 中的数组设置为零。
有什么解释吗?
顺便说一句,我搜索了 C++ 11 草案 n3242,但第 8.5 章 zero-initialize 和 default-initialize 似乎没有涵盖这种情况。我错过了什么吗?
最佳答案
FrameA() 将对对象进行值初始化 (§5.2.3/2):
The expression
T(), whereTis a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified)voidtype, creates a prvalue of the specified type, which is value-initialized
对没有用户提供的构造函数的非 union 类类型进行值初始化会将其零初始化 (§8.5/7):
if
Tis a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, ifT’s implicitly-declared default constructor is non-trivial, that constructor is called.
这会对其每个成员进行零初始化。
对具有用户提供的构造函数的类类型进行值初始化将简单地调用构造函数(在您的情况下,它不会初始化数组)(§8.5/7):
if
Tis a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor forTis called (and the initialization is ill-formed ifThas no accessible default constructor);
关于c++ - 默认构造函数是否零初始化成员数组变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20638968/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
在我的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
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问
两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了