这个成语是什么,什么时候应该使用?它解决了哪些问题?当使用C++ 11时,成语是否会改变?
虽然在许多地方已经提到过,但我们没有任何单一的"它是什么"问题和答案,所以在这里.以下是前面提到的地方的部分列表:
c++ c++-faq copy-constructor assignment-operator copy-and-swap
我刚刚听完了Scott Meyers关于C++ 0x的软件工程电台播客采访.大多数新功能对我来说都很有意义,我现在对C++ 0x感到兴奋,除了一个.我仍然没有得到移动语义 ......它们究竟是什么?
如何为具有unique_ptr成员变量的类实现复制构造函数?我只考虑C++ 11.
我正在实现一个简单的智能指针,它基本上跟踪它处理的指针的引用数量.
我知道我可以实现移动语义,但我不认为复制智能指针非常便宜.特别是考虑到它引入了产生令人讨厌的错误的机会.
这是我的C++ 11代码(我省略了一些不必要的代码).欢迎提出一般性意见.
#ifndef SMART_PTR_H_
#define SMART_PTR_H_
#include <cstdint>
template<typename T>
class SmartPtr {
private:
struct Ptr {
T* p_;
uint64_t count_;
Ptr(T* p) : p_{p}, count_{1} {}
~Ptr() { delete p_; }
};
public:
SmartPtr(T* p) : ptr_{new Ptr{p}} {}
~SmartPtr();
SmartPtr(const SmartPtr<T>& rhs);
SmartPtr(SmartPtr<T>&& rhs) =delete;
SmartPtr<T>& operator=(const SmartPtr<T>& rhs);
SmartPtr<T>& operator=(SmartPtr<T>&& rhs) =delete;
T& operator*() { return *ptr_->p_; }
T* operator->() { return ptr_->p_; }
uint64_t Count() const { return ptr_->count_; }
const T* …Run Code Online (Sandbox Code Playgroud) 请在下面找到我的代码,我曾经调用移动构造函数(代码灵感来自其他网站)并让我知道它有什么问题,我使用的是GCC 4.5.3
#include <iostream>
#include <vector>
class Int_Smart_Pointer {
int *m_p;
public:
Int_Smart_Pointer() {
std::cout<<"Derfault Constructor"<< std::endl;
m_p = NULL;
}
explicit Int_Smart_Pointer(int n) {
std::cout<<"Explicit Constructor: " << n <<std::endl;
m_p = new int(n);
}
Int_Smart_Pointer(const Int_Smart_Pointer& other) {
std::cout<<"Copy Constructor: "<<std::endl;
if(other.m_p)
m_p = new int(*other.m_p);
else
m_p = NULL;
}
Int_Smart_Pointer(Int_Smart_Pointer&& other) {
std::cout<<"Move Constructor: "<<std::endl;
m_p = other.m_p;
other.m_p = NULL;
}
Int_Smart_Pointer& operator=(const Int_Smart_Pointer& other) {
std::cout<<"Copy Assignment"<< std::endl;
if(this != &other) {
delete m_p; …Run Code Online (Sandbox Code Playgroud) 我最近了解了移动构造函数,但很多在线资源都没有讨论复制省略。复制省略对我来说也很有意义,但它让我想知道何时会在没有超级人为示例的情况下调用移动构造函数。
从一个流行的 SO 帖子向我解释了移动语义/sf/answers/217698701/
string b(x + y);
string c(some_function_returning_a_string());
Run Code Online (Sandbox Code Playgroud)
帖子说这两个都应该调用移动构造函数,因为它们接受临时变量。但是,这些实际上都没有调用移动构造函数(我已经测试过),相反,它们都只是执行复制省略,除非您通过显式编写std::move.
string b(std::move(x + y));
string c(std::move(some_function_returning_a_string()));
Run Code Online (Sandbox Code Playgroud)
或some_function_returning_a_string返回std::move(someString)。但你为什么要这样做?复制省略甚至比移动语义更高效。那么在什么情况下会调用移动构造函数而不是复制省略呢?
在你指出我这里之前,我觉得什么时候移动构造函数被调用?答案给出了人为的例子,或者他们中的一些人只是做了复制省略。我有兴趣学习在实践中何时调用移动构造函数。