不,移动语义不能在C ++ 98中实现。
我可以使用C ++ 98中的复制构造函数和赋值运算符来模拟移动构造函数和移动赋值运算符功能,以提高性能,只要我知道复制构造函数和复制赋值将仅针对代码中的临时对象调用,或者我正在插入针在我眼里?
我已经举了两个例子,一个是普通的复制构造函数和复制赋值运算符,另一个模拟了移动构造函数和移动赋值运算符,并在向量中推入10000个元素以调用复制构造函数。
普通副本构造函数和副本分配运算符的示例(copy.cpp)
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class MemoryBlock
{
public:
// Simple constructor that initializes the resource.
explicit MemoryBlock(int length)
: _length(length)
, _data(new int[length])
{
}
// Destructor.
~MemoryBlock()
{
if (_data != NULL)
{
// Delete the resource.
delete[] _data;
}
}
//copy constructor.
MemoryBlock(const MemoryBlock& other): _length(other._length)
, _data(new int[other._length])
{
std::copy(other._data, other._data + _length, _data);
}
// copy assignment operator.
MemoryBlock& operator=(MemoryBlock& other)
{
//implementation of copy assignment
}
private:
int _length; // The length of the resource.
int* _data; // The resource.
};
int main()
{
// Create a vector object and add a few elements to it.
vector<MemoryBlock> v;
for(int i=0; i<10000;i++)
v.push_back(MemoryBlock(i));
// Insert a new element into the second position of the vector.
}
带有复制构造函数和复制赋值运算符的模拟移动构造函数和移动赋值运算符功能的示例(move.cpp)>] >>#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class MemoryBlock
{
public:
// Simple constructor that initializes the resource.
explicit MemoryBlock(int length=0)
: _length(length)
, _data(new int[length])
{
}
// Destructor.
~MemoryBlock()
{
if (_data != NULL)
{
// Delete the resource.
delete[] _data;
}
}
// Move constructor.
MemoryBlock(const MemoryBlock& other)
{
// Copy the data pointer and its length from the
// source object.
_data = other._data;
_length = other._length;
// Release the data pointer from the source object so that
// the destructor does not free the memory multiple times.
(const_cast<MemoryBlock&>(other))._data = NULL;
//other._data=NULL;
}
// Move assignment operator.
MemoryBlock& operator=(const MemoryBlock& other)
{
//Implementation of move constructor
return *this;
}
private:
int _length; // The length of the resource.
int* _data; // The resource.
};
int main()
{
// Create a vector object and add a few elements to it.
vector<MemoryBlock> v;
for(int i=0; i<10000;i++)
v.push_back(MemoryBlock(i));
// Insert a new element into the second position of the vector.
}
我观察到性能有所提高,但要付出一些代价:
$ g++ copy.cpp -o copy
$ time ./copy
real 0m0.155s
user 0m0.069s
sys 0m0.085s
$ g++ move.cpp -o move
$ time ./move
real 0m0.023s
user 0m0.013s
sys 0m0.009s
我们可以看到,性能会有所提高。
我知道副本构造函数时,是否可以使用C ++ 98中的复制构造函数和赋值运算符来模拟移动构造函数和移动赋值运算符功能以提高性能?
不,移动语义不能在C ++ 98中实现。
具有移动语义的主要内容是如何管理内存。为此,专门设计和实现了一个解决方案(移动构造函数和移动赋值运算符)。
根据设计,模拟会出错。并且很可能无法复制真实的东西。
最好的解决方案是升级到更新的C ++。如果这不可能,请寻找其他优化方法,因为移动语义不可行。
不,移动语义不能在C ++ 98中实现。