mardi 23 août 2022

What is the best practice of defining and using classes in c++? [closed]

Hello guys i am new in c++ and there're some things that makes me confused so i wanted to consult you.

#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class A {
    public :
    A() { cout << "constructor called" << endl;}
    ~A() { cout << "destructor called" << endl;}
    A(A&&) {cout << "move constructor called"<< endl; return;}
    A& operator=(A&&) {cout << "move assignment operator called"<< endl; return *this;}

};
A fun() {
    A a; // 5. constructor called
    return a; // 6. move assignment operator called
    // 7. destructor called on this local a
}
void foo(A){
    return;
}
int main()
{
    A a; // 1. constructor called 
    A b; // 2. constructor called
    A c{std::move(b)}; // 3. move constructor called
    c = std::move(a); // 4. move assignment operator called
    a = fun();
    foo(std::move(c)); // 8. move constructor called

}

where the code is copied from

In c++ we're able to override many operators in classes and also there're some concepts called "copy cosntructor, copy assignment, move assignment, move constructor etc.
There may be some certain cases that would be appropriate to use these concepts but in general wouldn't be easy to access classes via pointers? class *A = new A(); thus any subsequent assignment movement or any operation would easily be performed as if it was a built in type.

Since any modern oop languages(java, c# and others) comply with this simple idea i think this feature of c++ is a little obsolete and confusing.(it's good to have for flexibility tho.)
What do you think?
What is the best practice here?
Is it really a good practice to make the user-defined types as if they were built in types and force them to act like them?

Aucun commentaire:

Enregistrer un commentaire