如何在堆内存上创建 class 的实例

How to create an Instance of a class on heap memory

已经为您定义了一个名为 "Pair" 的 class 类型。您需要编写一个名为 pairFactory 的函数来在堆上创建一个 Pair 实例。不要在堆栈上创建对象。然后,您的函数需要 return 一个指向该创建对象的指针。

我已经编写了 pairFactory 的代码。似乎 运行,但我收到 InfraError。 请帮我找出我的错误。 另外,我需要在堆内存中创建对象。

#include <iostream>

// This class Pair has already been defined for you.
// (You may not change this definition.)
class Pair {
public:
  int first, second;
  void check() {
    first = 5;
    std::cout << "Congratulations! The check() method of the Pair class \n has executed. (But, this isn't enough to guarantee \n that your code is correct.)" << std::endl;
  }
};

Pair *pairFactory() {
  //
    Pair P;
    P.check();
  // (You can use as many lines as you want.)
  return &P;
}

// Your function should be able to satisfy the tests below. You should try
// some other things to convince yourself. If you have a bug in this problem,
// the usual symptom is that after you submit, the grader will crash with a
// system error. :-)
int main() {
    Pair *p;
    p = new pairFactory();

  // This function call should work without crashing:
  p->check();

  // Deallocating the heap memory. (Assuming it was made on the heap!)
  delete p;

  std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;

  return 0;
}

你搞反了。您的工厂需要在堆上进行分配。您正在做的是返回一个不再存在的函数局部对象的地址。

Pair *pairFactory() {
  return new Pair;
}

然后在你的主函数中:

Pair *p = pairFactory();

你return在这里引用局部变量。

Pair *pairFactory() {
    Pair P;
    P.check();
  return &P; // Dangling pointer
}

所以一旦你离开函数,你就有了悬挂指针。

你必须打电话给new

Pair *pairFactory()
{
  return new Pair{};
}

主要内容可能如下所示:

int main() {
  Pair* p = pairFactory();

  // This function call should work without crashing:
  p->check();

  // Deallocating the heap memory. (Assuming it was made on the heap!)
  delete p;

  std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}

最好使用智能指针,这样就不必自己管理内存了:

std::unique_ptr<Pair> pairFactory()
{
    return std::make_unique<Pair>();
}

int main() {
    auto p = pairFactory();

    p->check();
    std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}

你完全按照告诉你的去做了没有去做:

Pair *pairFactory() {
    Pair P; // <----- creates an instance of Pair on the stack
    …
}

本练习的目的可能是测试您对 new 运算符的了解。看这里https://en.cppreference.com/w/cpp/memory/new/operator_new

函数

Pair *pairFactory() {
    return &P;
}

returns 指向本地堆栈上内存的指针,一旦它 returns 到 main() 就会被销毁/无效。