C++特性:移动,placement new


#include <iostream>
#include <vector>
#include <thread>
using namespace std;


class Test {
public:
    Test(string& label_) :label(label_){}
    Test(string&& label_):label(move(label_)){}
    // copy constructor
    Test(const Test& other) :label(other.label)
    {
        cout << "copy constructor" << endl;
    }
    // move constructor
    Test(Test&& other) :label(move(other.label))
    {
        cout << "move constructor" << endl;
    }

    // copy assign
    Test& operator=(const Test& other)
    {
        cout << "copy assign" << endl;
        label = other.label;
        return *this;
    }

    // move assign
    Test& operator=(Test&& other) noexcept
    {
        cout << "move assign" << endl;
        label = move(other.label);
        return *this;
    }
    void reset(const Test& other)
    {
        new(this) Test(other);
    }
    string getLabel()
    {
        return label;
    }
    
private:
    string label;
};
int main()
{
    Test firstTest("extra juicy");
    Test secondTest(firstTest);
    Test thirdTest(move(firstTest));

    // copy assign
    secondTest = thirdTest;
    // move assign
    firstTest = move(thirdTest);

    std::cout << "firstTest address:" << &firstTest << std::endl;
    std::cout << "firstTest:" << firstTest.getLabel() << std::endl;
    std::cout << "**************************************************" << std::endl;

    //placement new
    Test* ptr = new(&firstTest) Test("placement new");

    std::cout << "ptr address: " << &(*ptr) << std::endl;
    std::cout << "ptr:" << ptr->getLabel() << std::endl;

    std::cout << "**************************************************" << std::endl;

    // reset
    Test testReset("test reset");
    ptr->reset(testReset);
    std::cout << "ptr address: " << &(*ptr) << std::endl;
    std::cout << "ptr:" << ptr->getLabel() << std::endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值