题解 | #移动构造函数#

移动构造函数

http://www.nowcoder.com/questionTerminal/828075a0f90244a49c019715e01f3930



#include <iostream>
#include <string>

class A {
public:
    //构造函数
    A(const std::string& str)
    {
        _s = new std::string(str);
    }
    A(){}
    //重载赋值运算
    void operator=(const std::string& str)
    {
        if (_s) delete _s;
        _s = new std::string(str);
    }
    //移动构造函数
    A(std::string&& str)
    {
        if (_s) delete _s;
        _s = &str;
        //delete& str;
    }
    std::string s() const {
        return *_s;
    }
private:
    std::string* _s;
};

int main() {
    std::string input;
    std::cin >> input;
    A a(input);
    A b(std::move(a));
    std::cout << b.s() << std::endl;
    A c;
    c = std::move(b);
    std::cout << c.s() << std::endl;
    return 0;
}
全部评论

相关推荐

05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务