在指针方式和非指针方式之间选择哪一个


#include <iostream>
class A{
public:
A(){std::cout << "basic constructor called n";};
A(const A& other) {
    val = other.x
    std::cout << "copy constructor is called n";
}
A& operator=(const A& other){
    val = other.x
    std::cout << "nnassignment operator " << other.val << "nn"; 
}
~A(){
    std::cout << "destructor of value " << val <<" called !!n";
}

A(int x){
    val = x;
    std::cout << " A("<<x<<") constructor called n";
}
int get_val(){
    return val;
}
private: 
int val;
};
int main(){
    // non pointer way
    A a;
    a = A(1);
    std::cout << a.get_val() << std::endl;
    a = A(2);
    std::cout << a.get_val() << std::endl;
    // pointer way
    A* ap;
    ap = new A(13);
    std::cout << ap->get_val() << std::endl;
    delete ap;
    ap = new A(232);
    std::cout << ap->get_val() << std::endl;
    delete ap;
    return 0;
}

我最初从默认构造函数中创建一个对象,然后将 tmp r 值对象A(x)分配给a。这最终调用assignment operator.因此,在这种方法中涉及3个步骤

非指针方式

1) 构造函数

2) 赋值运算符

3) 析构函数

当我使用指针时,它只需要两个步骤

指针方式

1) 构造函数

2) 析构函数

我的问题是我应该使用非指针方式创建新类还是应该使用指针方式。因为有人说我应该避免指针(我知道我也可以在这里使用shared_ptr)。

经验法则:更喜欢在堆栈上创建对象。在堆栈上创建对象时,内存管理的工作较少。它也更有效率。

何时必须在堆上创建对象?

以下是一些需要它的情况:

  1. 您需要创建一个对象数组,其中数组的大小仅在运行时已知。

  2. 你需要一个对象存在于构造它的函数之外。

  3. 您需要存储和/或传递指向基类类型的指针,但指针指向派生类对象。在这种情况下,派生类对象很可能需要使用堆内存创建。

最新更新