c++构造函数

#include 
#include 
#include 

class Example {
public:
    Example(std::string *mess) : mess(mess) {
        std::cout << "Example() -> this = " << this << std::endl;
    }
    ~Example() {
        std::cout << "~Example() -> this = " << this << std::endl;
        if(mess != nullptr)
        {
            delete mess;
        }
    }
    Example(const Example &ex) {
        mess = new std::string(*ex.mess);
        std::cout << "Example(const Example &ex) -> this = " << this << std::endl;
    }
    Example &operator =(const Example &ex) {
        if(this == &ex)
        {
            return *this;
        }
        if(mess != nullptr)
        {
            delete mess;
        }
        mess = new std::string(*ex.mess);
        std::cout << "Example &operator =(const Example &ex) -> this = " << this << std::endl;
        return *this;
    }
    Example(Example &&ex) {
        mess = ex.mess;
        ex.mess = nullptr;
        std::cout << "Example(Example &&ex) -> this = " << this << std::endl;
    }
    Example &operator =(Example &&ex) {
        if(mess != nullptr)
        {
            delete mess;
        }
        mess = ex.mess;
        ex.mess = nullptr;
        std::cout << "Example &operator =(Example &&ex) -> this = " << this << std::endl;
        return *this;
    }
    std::string *ptr() const {
        return mess;
    }
private:
    std::string *mess;
};

Example &&valueType() {
    std::cout << "---------------valueType---------------" << std::endl;
    Example ex(new std::string("nice to meet you!"));
    return std::move(ex);
}

#if 0
void func(Example &&ex) {

}
#else
void func(Example ex) {
    std::cout << "---------------func---------------" << std::endl;
    std::cout << "ex.ptr() = " << ex.ptr() << std::endl;
    std::cout << "string = " << *ex.ptr() << std::endl;
}
#endif

void test() {
//    Example ex(new std::string("hello, world"));
//    std::cout << "ex.ptr() = " << ex.ptr() << std::endl;
//    func(std::move(ex));
//    std::cout << "ex.ptr() = " << ex.ptr() << std::endl;
//    func(valueType());
    Example pex = valueType();
    pex = valueType();
}

int main()
{
    test();
    return 0;
}

你可能感兴趣的:(c++)