【问题标题】:Why are there dynamic memory allocation in class and main() function too为什么类和 main() 函数中也有动态内存分配
【发布时间】:2020-06-27 20:41:00
【问题描述】:
#include<iostream>
#include<cstring>
using namespace std;

class Employee
{
private:
    char *firstName;
    char *lastName;
    static int count;
public:
    Employee( const char * const first, const char * const last){
        firstName = new char[ strlen( first ) + 1 ];
        strcpy( firstName, first );

        lastName = new char[ strlen( last ) + 1 ];
        strcpy( lastName, last );

        count++;
        cout << "Employee constructor for " << firstName
             << ' ' << lastName << " called." << endl;
    }
    ~Employee(){
        cout << "~Employee() called for " << firstName
             << ' ' << lastName << endl;

        delete [] firstName; // release memory                                                                     
        delete [] lastName; // release memory                                                                      
        count--;
    }
    const char *getFirstName() const{
        return firstName;
    }
    const char *getLastName() const{
        return lastName;
    }
    static int getCount(){
        return count;
    }
}; // end class Employee                                                                                           

int Employee::count = 0;

main(){
    cout<<"Count = "<<Employee::getCount()<<endl;
    Employee *e1Ptr = new Employee( "Ahmad", "Ali" );
    Employee *e2Ptr = new Employee( "Saeed", "Khalid" );
    cout<<"Count = "<<e1Ptr->getCount()<<endl;
    cout << "\n\nEmployee 1: "
         << e1Ptr->getFirstName()<<" "<<e1Ptr->getLastName()
         << "\nEmployee 2: "
         << e2Ptr->getFirstName()<<" "<<e2Ptr->getLastName()<<"\n";
    delete e1Ptr;
    e1Ptr = 0;
    delete e2Ptr;
    e2Ptr = 0;
    cout<<"Count = "<<Employee::getCount()<<endl;
    system("pause");
}

Q- 为什么我们需要在 main() 和 class 中进行动态内存分配?在类定义或 main() 函数中分配动态内存是否不够?

Q- 为什么 e1Ptr = 0;而 e2Ptr = 0;正在使用中。

我是新手。所以,请详细说明一下。谢谢

【问题讨论】:

  • 忘记 C。C++ 是一种完全不同的语言。
  • 没有任何需要......这只是糟糕的编程。 …… PS:main 在 C++ 中需要 int 的返回类型
  • 在 C++ 中,您应该始终使用智能指针(例如 std::unique_ptr、std::shared_ptr、...),而不是手动分配内存。阅读:en.cppreference.com/book/intro/smart_pointers
  • 阅读 good C++ programming book,然后是 C++11 标准 n3337,然后是 C++ 编译器(例如 GCC...)和调试器(例如 GDB)的文档。 ..)
  • @LHLaurini。我绝对同意。但也需要大量的练习。见norvig.com/21-days.html

标签: c++ memory dynamic allocation


【解决方案1】:

这很简单。 new Employee( "Ahmad", "Ali" )Employee 类的实例分配内存并初始化,new char[ strlen( first ) + 1 ]; 在类内部分配一个字符串。

然而,那是糟糕的 C++ 代码。您应该很少直接管理内存,而是使用类来帮助您。这些被称为智能指针,将根据需要自动分配、初始化、销毁和取消分配。手动管理原始指针容易出错且不必要。请记住:您编写的代码越少,可能出现错误的地方就越少。

因此,而不是

Employee *e1Ptr = new Employee( "Ahmad", "Ali" );

你会使用

std::unique_ptr<Employee> e1Ptr = std::make_unique<Employee>("Ahmad", "Ali");

auto e1Ptr = std::make_unique<Employee>("Ahmad", "Ali");

并删除delete

此外,您可以使用std::string,而不是分配字符串。所以不是

char* firstName = new char[ strlen( first ) + 1 ];
strcpy( firstName, first );

你会使用

std::string firstName = first;

(也删除delete[]

【讨论】:

  • 好的,我的问题是“new Employee("Ahmad", "Ali")"" 是否为 Employee 类的实例分配内存并初始化它。这意味着该对象已经被创建和初始化这里也一样。那么,这里需要构造函数来初始化一个对象和一个字符串动态内存吗?
  • @RizwanMuzaffar main 中的每个 new 创建一个 Employee 类的实例。构造函数中的每个new 创建一个字符数组。所以你最终得到了Employee 类的两个实例(*e1Ptr*e2Ptr)和四个字符数组(e1Ptr-&gt;firstNamee1Ptr-&gt;lastNamee2Ptr-&gt;firstNamee2Ptr-&gt;lastName),每个@987654342 两个@。但同样,除非您有理由这样做,否则不要直接分配内存。我绝对建议您找到一本好的 C++ 书籍或教程。请记住,C 和 C++ 是不同的语言:避免使用任何标记为“C/C++”的语言。
  • 这个语句需要什么? e1Ptr = 0;
  • @RizwanMuzaffar 不多,但它避免了意外取消引用刚刚释放的指针(如果指针为空,则更容易调试崩溃)。此外,虽然它仍然有效,但最好使用nullptr。同样,如果您使用std::unique_ptr,则不必关心它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2023-03-07
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多