我有一个奇怪的问题:
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()
}
给出以下对象
(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 = {__d = {__d = {__r = 14207749597) }},{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 = 1427720}}1427720}14277204 ,{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 = 14270724}}}}59977
1、理论上,20 个 UserType 对象中的每一个都应该有不同且唯一的 time_since_epoch().count(),但在 gdb 输出中,它们都是相同的。
2,我在这里尝试了相同的代码:http: //melpon.org/wandbox并且每个对象都有一个唯一的时间戳。所以我正在观察不同的行为。
3、一些分析:pre.push_back(UserType())中的UserType();是一个右值;然后编译器将值复制(通过复制构造函数)右值到向量 pre 中的左值对象中。编译器是否有可能看到常量循环号 20 和右值对象指令,因此决定“同时”创建 20 个对象作为优化?即使是这种情况,编译器也不太可能同时进行构造——不存在同时进行的事情——只有可以忽略的微小差异。我不认为编译器可以在 stable_clock 的 1 个刻度内完成 20 个对象构造。
4,这是我的 Makefile 中的相关编译标志 - 请注意,我没有要求编译器进行优化:-g -Wall -std=gnu++0x
5,这段代码(20个对象构造的循环)在google测试文件中;我的编译器是 cygwin 上的 g++ 4.8.3。
我的问题是:
这里发生了什么?具体来说,为什么我看到构建 20 个对象的相同时间戳?
非常感谢。
/*******************根据请求,UserType实现*********************/
class UserType
{
public:
UserType()
{
timePoint_ = std::chrono::steady_clock::now();
}
bool operator==(const UserType other) const
{
return timePoint_ == other.timePoint_;
}
friend std::ostream& operator<<(std::ostream& out, UserType type);
protected:
std::chrono::time_point<std::chrono::steady_clock> timePoint_;
};
std::ostream& operator<<(std::ostream& out, UserType type)
{
out << type.timePoint_.time_since_epoch().count() << std::endl;
return out;
}