C++拷贝和移动

一、赋值

1.使拷贝赋值非virtual,以const& 传参,并返回非const的引用

2.使移动赋值非virtual,以&&传参,并返回非const的引用

// 拷贝赋值
vector& operator = (const vector& other);

// 移动赋值
vector& operator = (vector&& other);  //C++17前
vector& operator = (vector&& other) noexcept;  //C++17起

3.移动操作使用noexcept.一个noexcept声明的函数对编译器来说是个优化机会。

vector(vector&& other) noexcept;   //C++17起
vector& operator = (vector&& other) noexcept;  //C++17起

二、自赋值

1.使拷贝赋值对自赋值安全

2.使移动赋值对自赋值安全

自赋值安全意味着操作x=x不应该改变x的值

对于STL容器、std::string和内置类型,如int等,拷贝/移动赋值对于自赋值是安全的。自动生成的拷贝/移动赋值运算符对于自赋值也是安全的。使用自赋值安全的类型自动生成的拷贝/移动赋值运算符也是如此。

class Foo
{
    std::string s;
    int i;
public:
    Foo& Foo::operator = (const Foo& a)
    {
        s = a.s;
        i = a.i;
        return *this;
    }

    Foo& Foo::operator = (Foo&& a) noexcept
    {
        s = std::move(a.s);
        i = a.i;
        return *this;
    }
};

这种情况下,任何多余、高开销的自赋值检查都会不必要地让性能变差。

class Foo
{
    std::string s;
    int i;
public:
    Foo& Foo::operator = (const Foo& a)
    {
        if (this == &a)  return *this;   //多余的自赋值检查
        s = a.s;
        i = a.i;
        return *this;
    }

    Foo& Foo::operator = (Foo&& a) noexcept
    {
        if (this == &a)  return *this;   //多余的自赋值检查
        s = std::move(a.s);
        i = a.i;
        return *this;
    }

    //  ...
};

三、语义

1.拷贝操作应该进行拷贝

  • 在拷贝之后(a = b),a和b必须相同(a == b)。
  • 拷贝可深可浅。深拷贝意味着对象a和b之后是相互独立的(值语义)。浅拷贝意味着对象a和b之后共享一个对象(引用语义)。

2.移动操作应该进行移动,并使源对象处于有效状态。

  • C++标准要求被移动的对象之后必须处于一个未指定但有效的状态。通常情况下,这个被移动的状态是移动操作源对象的默认状态。

3.多态类应当抑制公开的拷贝/移动操作

拷贝一个多态类的操作可能会以切片而告终。切片是C++中最黑暗的部分之一。

// 切片意味着你想在赋值或初始化过程中拷贝一个对象,但你只得到该对象的一部分。举例:
struct Base
{
    int base{1998};
};

struct Derived : Base
{
    int derived{2011};
};

void needB(Base b)
{
    //...
}

int main()
{
    Derived d;
    Base b = d;   //(1)
    Base b2(d);   //(2)
    needB(d);     //(3)
}

表达式1,2,3,效果都相同,d的Derived部分被删除了

现在,它已经十分危险了,当你拷贝一个多态类时,切片就会发生。

#include <iostream>
#include <string>

struct Base
{
    virtual std::string getName() const
    {
        return "Base";
    }
}

struct Derived : Base
{
    std::string getName() const override
    {
        return "Derived";
    }
}

int main()
{
    std::cout << "\n";
    Base b;
    std::cout << "b.getName()" << b.getName() << "\n";

    Derived d;
    std::cout << "d.getName()" << d.getName() << "\n";

    Base b1 = d;
    std::cout << "b1.getName()" << b1.getName() << "\n";

    Base& b2 = d;
    std::cout << "b2.getName()" << b2.getName() << "\n";

    Base* b3 = new Derived;
    std::cout << "b3->getName()" << b3->getName() << "\n";

    std::cout << "\n";
}

在拷贝的情况下,编译器使用了声明的类型,即静态类型。如果你使用了间接手段,如引用或指针,那么当前类型,即动态类型,会被使用。

4.若要对多态类型进行深拷贝,应使用虚函数clone,而不是公开的拷贝构造/赋值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值