关于右值引用于对象生命周期的有关问题

关于右值引用于对象生命周期的问题
考虑下面的swap函数
当 T 为类对象(例如 clone_ptr)且实现了复制构造函数的右值引用优化和赋值“operator=”函数的右值引用优化时
swap函数能够通过拷贝clone_ptr类中的指针优化对象的拷贝过程。

随之而来的问题是
swap对非类对象类型(int, double。。。)是否作优化,如果有那是如何实现的。
按我的理解右值引用实际上是将类对象中指针指向的对象生命周期延长。如果类中不包含任何指针,或者未实现复制构造函数的右值引用优化,未实现赋值“operator=(T&&)”函数的右值引用优化,右值引用就起不到任何作用。




    template <class T> swap(T& a, T& b) 
    { 
        T tmp(std::move(a)); // move a to tmp 
        a = std::move(b);    // move b to a 
        b = std::move(tmp);  // move tmp to b 
     }


template <class T>  
class clone_ptr  
{  
private:  
    T* ptr;  
public:  
    // construction  
    explicit clone_ptr(T* p = 0) : ptr(p) {}  
   
    // destruction  
    ~clone_ptr() {delete ptr;}  
  
    // copy semantics  
    clone_ptr(const clone_ptr& p)  
  
        : ptr(p.ptr ? p.ptr->clone() : 0) {}  
  
    clone_ptr& operator=(const clone_ptr& p)  
    {  
        if (this != &p)  
        {  
            delete ptr;  
            ptr = p.ptr ? p.ptr->clone() : 0;  
        }  
        return *this;  
    }  
  
    // move semantics  
    clone_ptr(clone_ptr&& p)  
        : ptr(p.ptr) {p.ptr = 0;}  
   
    clone_ptr& operator=(clone_ptr&& p)  
    {  
        std::swap(ptr, p.ptr);  
        return *this;  
    }  
  
    // Other operations  
    T& operator*() const {return *ptr;}  
  
    // ...  
};  

------解决思路----------------------
出现新的东西就是为了解决之前不大好办的东西, 了解到这一点后, 什么东西就都好理解了.
------解决思路----------------------
swap为什么要对基础类型优化?怎么优化?
------解决思路----------------------
#include <new>

class PTR {
private :
int *ptr ;

PTR () {
ptr = new int () ;
}

explicit PTR (int i) {
ptr = new int (i) ;
}

~PTR () {
if (ptr)
delete ptr ;
}

PTR (const PTR &b) {
ptr = new int (*b.ptr) ;
}

inline PTR &operator= (const PTR &b) {
if (this == &b)
return *this ;
this->~PTR () ;
new (this) PTR (std::move (b)) ;
return *this ;
}

PTR (PTR &&b) {
ptr = b.ptr ;
b.ptr = 0 ;
}

inline PTR &operator= (PTR &&b) {
if (this == &b)
return *this ;
this->~PTR () ;
new (this) PTR (std::move (b)) ;
return *this ;
}
} ;

移动语义比拷贝语义快的原因在于,这个类拥有资源(如内存,如一个对象),移动构造时不需要创建新的资源
右值的存在周期是当前语句,而左值存在于这个语句块,而资源可以存在于整个程序运行时
一般访问资源需要一个资源的标识值,对于内存就是一个指针了,
多个标识符指向一个资源可能会引起问题,逻辑上我们拷贝一个类型,包括它的资源,而不是单纯的拷贝标识符
移动构造对于普通类型和拷贝构造并无区别,但它不拷贝资源,只是获得右值的资源标识符,然后将右值的资源标识符设为无效