如何在堆内存中创建类的实例

问题描述 投票:0回答:3

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

我已经编写了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;
}
c++ class instance
3个回答
2
投票

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

Pair *pairFactory() {
  return new Pair;
}

然后在您的主要功能中:

Pair *p = pairFactory();

2
投票

您在此处返回对局部变量的引用。

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;
}

1
投票

您的操作完全符合您的要求,[

Pair *pairFactory() { Pair P; // <----- creates an instance of Pair on the stack … }
此练习的目的可能是测试您对new运算符的了解。看到这里https://en.cppreference.com/w/cpp/memory/new/operator_new
© www.soinside.com 2019 - 2024. All rights reserved.