只是一个问题。查看 C++ Boost 库(特别是 boost::thread 类),我最终想到:“如何创建一个定义不能复制但可以从函数返回的对象的类?”
考虑一下这个例子,boost::thread 类具有我之前提到的特性,因此可以这样做:
boost::thread make_thread();
void f()
{
boost::thread some_thread=make_thread();
some_thread.join();
}
好吧,这意味着对象 boost::thread 不能被复制,而是从一个函数返回,这是可能的。 这怎么可能????
我想一定不能提供复制构造函数,但是如何处理从函数返回?不需要用拷贝构造函数吗???
谢谢
最佳答案
这在 C++1x 中是可能的,它通过右值引用提供移动语义。使用它,您可以分别实现移动和/或复制:
class my_class {
private:
data_t* data_;
public:
my_class(const my_class& rhs) // copy constructor
: data_(rhs.data_.clone())
{}
my_class(my_class&& rhs) // move constructor
: data_(rhs.data_)
{
rhs.data_ = NULL;
}
~my_class() {delete data_;} // noop if data_==NULL
my_class& operator=(my_class rhs) // copy assignment
{
this->swap(rhs);
}
my_class& operator=(my_class&& rhs)// move assignment
{
this->swap(rhs);
}
// ...
};
可以分别禁止复制和移动,所以可以设置可以移动但不能复制的类。
当然,即使您的编译器尚不支持移动语义(std::auto_ptr
,毕竟在分配给),因此即使没有移动语义,这也可能适用于 boost::thread
。
关于c++ - 在 C++ 中创建不可复制但可移动的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4260209/