lundi 30 mars 2015

Objects created at the same time - unwanted compiler optimization?

I've got a weird problem:



for (size_t i=0; i<20; i++)
{
// pre is a vector<UserType>
pre.push_back(UserType()); // In UserType constructor, record std::chrono::steady_clock::now()
}


gives the following objects



(gdb) print pre $1 = std::vector of length 20, capacity 32 = {{timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}, {timePoint_ = {__d = { __r = 1427724945979761000}}}, {timePoint_ = {__d = {__r = 1427724945979761000}}}, { timePoint_ = {__d = {__r = 1427724945979761000}}}}



1, Theoretically, each of the 20 UserType objects should have different & unique time_since_epoch().count(), but in the gdb outputs, they're all the same.


2, I tried the same code here: http://ift.tt/1bJo30l and each object has a unique time stamp. So I'm observing different behaviours.


3, Some analysis: UserType() in pre.push_back(UserType()); is an rvalue; the compiler then value-copies(via copy constructor) the rvalue into an lvalue object in the vector pre. Is it possible that the compiler sees the constant loop number 20 and the rvalue object instructions, therefore decides to create 20 object "at the same time" as an optimization? Even if this is the case, it's not likely that the compiler can do construction all at the same time - there's no such thing as the same time - only small differences that can be ignored. I don't think the compiler can do 20 object constructions within 1 single tick of steady_clock.


4, Here's the relevant compilation flags in my Makefile - note that I did NOT ask the compiler to optimize: -g -Wall -std=gnu++0x


5, This piece of code(loop of 20 object constructions) was in a google test file; My compiler is g++ 4.8.3 on cygwin.


My questions is:


What is going on here? Specifically, why am I seeing the same time stamps for constructing the 20 objects?


Thanks a lot.


Aucun commentaire:

Enregistrer un commentaire