Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c++ - What operators do I have to overload to see all operations when passing an object to a function?

I would like to write a piece of code that shows all copy/assignment/delete etc. operations that are done on the object when passing it to a function.

I wrote this:

#include <iostream>

class A {
    public:
        A(){std::cout<<"A()"<<std::endl;}
        void operator=(const A& a ){std::cout<<"A=A"<<std::endl;}
        A(const A& a){std::cout<<"A(A)"<<std::endl;}
        ~A(){std::cout<<"~A"<<std::endl;}
};

void pv(A a){std::cout<<"pv(A a)"<<std::endl;}
void pr(A& a){std::cout<<"pr(A& a)"<<std::endl;}
void pp(A* a){std::cout<<"pp(A* a)"<<std::endl;}
void pc(const A& a){std::cout<<"pc(const A& a)"<<std::endl;}

int main() {
    std::cout<<" -------- constr"<<std::endl;
    A a = A();
    std::cout<<" -------- copy constr"<<std::endl;
    A b = A(a);
    A c = a;
    std::cout<<" -------- assignment"<<std::endl;
    a = a;    
    a = b;
    std::cout<<" -------- pass by value"<<std::endl;
    pv(a);
    std::cout<<" -------- pass by reference"<<std::endl;
    pr(a);
    std::cout<<" -------- pass by pointer"<<std::endl;
    pp(&a);
    std::cout<<" -------- pass by const reference"<<std::endl;
    pc(a);
    return 0;
}

Did I forget anything? Is there anything else that has to be considered when comparing the different ways of passing an object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C++11, you should add rvalue reference:

A(A&&);
void operator=(A&& a );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...