c++11总结09——右值引用避免深拷贝

问题代码:

class A
{
public:
	A() : m_ptr(new int(0))
	{
		cout << "construct" << endl;
	}

	A(const A& a) : m_ptr(new int(*a.m_ptr))
	{
		cout << "copy construct" << endl;
	}

	~A()
	{
		cout << "destruct" << endl;
		delete m_ptr;
	}

private:
	int* m_ptr = nullptr;
};

A Get()
{
	A a;
	return a;
}

int main()
{
	A a = Get();

	system("pause");
    return 0;
}

Get函数会返回临时变量,然后通过这个临时变量拷贝构造一个新的对象,临时对象在拷贝构造之后就销毁了,如果堆内存很大,拷贝构造的代价也就会很大。

优化代码:

class A
{
public:
	A() : m_ptr(new int(0))
	{
		cout << "construct" << endl;
	}

    A(const A& a) : m_ptr(new int(*a.m_ptr))
	{
		cout << "copy construct" << endl;
	}

	A(A&& a) : m_ptr(a.m_ptr)
	{
		a.m_ptr = nullptr;
		cout << "move construct" << endl;
	}

	~A()
	{
		cout << "destruct" << endl;
		delete m_ptr;
	}

private:
	int* m_ptr = nullptr;
};

这里没有用到拷贝构造,而是利用的是移动构造(Move ConStruct)。它的参数是一个右值引用类型的参数A&&,这里没有深拷贝,只有浅拷贝,这样避免了临时对象的深拷贝,提高了性能。

移动语义可以将资源(堆、系统对象等)通过浅拷贝的方式从一个对象转移到另一个对象,减少不必要的临时对象的创建、拷贝与销毁,提高了c++应用程序的性能。

move语义

std::move: 将对象的状态或者所有权从一个对象转移到另一个对象,只是转移,没有内存拷贝。本质上是将左值强制转换为右值引用。

示例如下:

inline String& String::operator(const String& str)
{
    if (this == &str)
        return *this;

    delete[] m_data;
    m_data = new char[strlen(str.m_data) + 1];
    strcpy(m_data, str.m_data);
    return *this;
}

本例为String类的一个拷贝赋值函数,它的具体流程为:

1)删除m_data的资源

2)赋值str中的临时对象

3)销毁str中的临时对象,释放资源

c++11实现方式:

inline String& String::operator(const String&& str)
{

//转移资源控制权

}

你可能感兴趣的:(c++11/17,深拷贝)