vendredi 3 février 2017

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).

Aucun commentaire:

Enregistrer un commentaire