我创建了一个函数来计算2个timeval函数的差。这是该功能的基本版本。
struct timeval* getDifference(struct timeval* startTime, struct timeval* finishTime)
{
struct timeval* difference = new struct timeval;
difference->tv_sec = finishTime->tv_sec - startTime->tv_sec;
difference->tv_usec = finishTime->tv_usec - startTime->tv_usec;
return difference;
}
int main()
{
struct timeval a,b;
struct timeval* c;
gettimeofday(&a, NULL);
usleep(100000);
gettimeofday(&b, NULL);
c = getDifference(&a, &b);
}
我想知道的是
struct timeval* c;
使用是否安全?还是应该像struct timeval* c = new struct timeval;
?如果安全的话,释放
c
会释放函数内部分配的difference = new struct timeval;
吗? 最佳答案
我建议您完全不使用指针。让参数作为引用复制返回值:
struct timeval getDifference(const struct timeval& startTime, const struct timeval& finishTime)
{
struct timeval difference;
difference.tv_sec = finishTime.tv_sec - startTime.tv_sec;
difference.tv_usec = finishTime.tv_usec - startTime.tv_usec;
return difference;
}