c++设置 timeval 成员
我有一个函数,它接受两个当前类级别的成员变量并将它们设置为 timeval 结构,并返回 timeval obj (按值)。
我在设置类级别成员 timeval 对象与在每次 get() 调用时创建新的 timeval 对象时遇到问题。
在类内部
protected:
int time[2];
timeval tv;
// work done on setting the time array
timeval getTimeval()
{
tv.tv_sec = (time_t)time[0];
tv.tv_usec = time[1];
return tv;
}
这不会返回正确的 timeval 值。 tv.tv_sec 将被覆盖,但 tv_usec 保持不变。但是,当我在 get 调用中创建 timeval 对象时,它将返回正确的值。
timeval getTimeval()
{
timeval t;
t.tv_sec = (time_t)time[0];
t.tv_usec = time[1];
return t;
}
是否有任何理由在成员变量上设置 timeval 对象应该不同于创建新对象并设置其值?
I have a function which takes two current class level member variables and sets them into a timeval structure, and returns the timeval obj (by value).
I am seeing an issue when setting a class level member timeval object vs creating a new timeval object at each get() call.
Inside the class
protected:
int time[2];
timeval tv;
// work done on setting the time array
timeval getTimeval()
{
tv.tv_sec = (time_t)time[0];
tv.tv_usec = time[1];
return tv;
}
This will not return the correct timeval values. The tv.tv_sec will get overwritten but the tv_usec remains constant. However, it will return the correct values when I create the timeval object inside the get call.
timeval getTimeval()
{
timeval t;
t.tv_sec = (time_t)time[0];
t.tv_usec = time[1];
return t;
}
Is there any reason setting the timeval objects on a member variable should differ from creating a new object and setting its values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也就是说,这里确实没有理由将 timeval 作为类成员;您没有按原样优化任何内容(为了避免构造单独的实例,您必须通过引用而不是按值返回类成员),因此您只是浪费了类的每个实例内的空间。 (无论如何,按值返回 timeval 的成本并不是特别高;它是一个小型的 POD 结构,是通过堆栈分配的。)
但是为什么这些值首先从 int 数组中开始呢?为什么不仅仅拥有一个 timeval 数据成员并直接使用它(并通过访问器中的 const 引用返回它)?
That said, there's really no reason to have the timeval as a class member here; you aren't optimizing anything as is (to avoid constructing a separate instance, you would have to return the class member by reference, rather than by value) so you're just wasting space inside each instance of the class. (Returning the timeval by value isn't especially costly anyway; it's a small, POD struct, being stack-allocated.)
But why are the values starting out in the int array in the first place? Why not just have a timeval data member and work with it directly (and return it by const reference in the accessor)?
这对我来说工作得很好,我不明白你的代码中的问题出在哪里。因此,请给出您的意见(或编辑此代码),让我们知道实际问题。
this is working fine for me, i don't understand where is the problem in your code. So, please give your comments(or edit this code) to let us know the actual problem.