【问题标题】:Values is destroyed despite allocating on the heap [duplicate]尽管在堆上分配,但值被破坏[重复]
【发布时间】:2014-05-07 11:13:14
【问题描述】:

对不起,我以为我现在已经理解堆栈和堆了,但显然我错了。我声明了堆上的每个对象,但是当第一个方法完成时,我可以通过 std::cout 看到时间为零,即:

startTPtr: 00:00:00

当时间在函数中打印时它可以,但是在函数结束后它会以某种方式被破坏。

我在这里错过了什么重要的东西吗?我应该从函数中返回指针吗?

提前致谢!!!

int main() {

   Clock *_clockPtr = new Clock();

   MyTime *_startTPtr = new MyTime();
   MyTime *_endTPtr = new MyTime();

   char *ch = new char[100];

   start_app(_startTPtr, _endTPtr, _clockPtr, ch);

   cout << "startTPtr: " << *_startTPtr << endl;

return 0;
}

void start_app(MyTime *_startTPtr, MyTime *_endTPtr, Clock *clock, char *ch) {

   cout << "Press ENTER to start and finish!";
   int newLine = 0;
   for (std::string line; std::getline(std::cin, line); ) {

    if (newLine == 0) {
        std::cout << "... ";
        MyTime* myTime1 = new MyTime(clock->give_me_the_time()); 
        _startTPtr = myTime1;
        cin >> ch;
    } else {
        MyTime* myTime2 = new MyTime(clock->give_me_the_time()); 
        _endTPtr = myTime2;
        break;
    }
    cout << "startTPtr: " << *_startTPtr << endl;
    newLine++;
}
}

【问题讨论】:

标签: c++ pointers heap-memory stack-memory


【解决方案1】:

如果要更改函数中的参数并将其反映在函数的调用者中,则需要通过引用传递参数。否则,参数将被复制,您只需更改副本。

在您的start_app 函数中,您希望同时更改_startTPtr_endTPtr,因此您需要将它们作为指向MyTime 的指针的引用传递:

void start_app(MyTime *&_startTPtr, MyTime *&_endTPtr, Clock *clock, char *ch) { ... }

【讨论】:

  • 谢谢 :-) .. 将在 5 分钟内接受
  • 可以另一种方法是制作一个显式的复制构造函数吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2019-07-30
相关资源
最近更新 更多