pokche
pokche

Reputation: 1149

Which one to choose between pointer way and non pointer way?

#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 << "\n\nassignment operator " << other.val << "\n\n"; 
}
~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;
}

I initially create an object out of default constructor and then assign tmp r-value objects A(x) to a. This ends up calling assignment operator. So in this approach there are 3 steps involved

(non-pointer way)

1) constructor

2) assignment operator

3) destructor

Where as when I use pointer it only requires two step

(pointer way)

1) constructor

2) destructor

My question is should I use non-pointer way to create new classes or should I use pointer way. Because I have been said that I should avoid pointers (I know I could also use shared_ptr here).

Upvotes: 0

Views: 43

Answers (1)

R Sahu
R Sahu

Reputation: 206717

Rule of thumb: Prefer to create objects on the stack. There is less work for memory management when you create objects on the stack. It is also more efficient.

When do you have to create objects on the heap?

Here are some situations that need it:

  1. You need to create an array of objects where the size of the array is known only at run time.

  2. You need an object to live beyond the function in which it was constructed.

  3. You need to store and/or pass around a pointer to a base class type but the pointer points to a derived class object. In this case, the derived class object, most likely, will need to be created using heap memory.

Upvotes: 1

Related Questions