我正在实现一个简单的智能指针,它基本上跟踪它处理的指针的引用数量.
我知道我可以实现移动语义,但我不认为复制智能指针非常便宜.特别是考虑到它引入了产生令人讨厌的错误的机会.
这是我的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)不合成任何构造函数或赋值方法.我找到了一种方法来做这个,只是在类中包含一个const int成员,但这并没有让我感觉良好.是否有属性或某些东西表示这一点.
可能重复:
为什么C++ 11删除的函数参与重载解析?
我有两个关于以下C++ 11代码的问题:
#include <iostream>
using namespace std;
struct A {
A() { cout << "Default c-tor" << endl; }
A(const A&) { cout << "Copy c-tor" << endl; }
A(A&&) = delete;
};
A f()
{
A a;
return a;
}
int main()
{
A b = f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我用gcc和clang得到以下编译错误
gcc-4.7.2(g ++ --std = c ++ 11 main.cpp):
main.cpp: In function ‘A f()’:
main.cpp:16:9: error: use of deleted function ‘A::A(A&&)’
main.cpp:8:2: error: declared here
main.cpp: …
Run Code Online (Sandbox Code Playgroud) 在做了一些研究之后,我发现C++ 11的分配器存在缺陷,需要类型可移动/可复制.我确定这是导致这个问题的原因,但我对删除和未声明的移动语义之间的行为感到困惑.
我有以下代码无法在MSVC12和Clang上编译:
#include <vector>
class Copyable
{
public:
Copyable() = default;
Copyable(Copyable const& other)
: m_int(other.m_int)
{}
Copyable& operator= (Copyable const& other)
{
m_int = other.m_int;
return *this;
}
Copyable(Copyable&&) = delete;
Copyable& operator= (Copyable&&) = delete;
private:
int m_int = 100;
};
int main()
{
std::vector<Copyable> objects;
objects.push_back(Copyable{});
}
Run Code Online (Sandbox Code Playgroud)
这无法在MSVC上编译:
xmemory0(600):错误C2280:'可复制::可复制(可复制&&)':尝试引用已删除的函数
而对于Clang(现场样本):
new_allocator.h:120:23:错误:调用'Copyable'的已删除构造函数
在这两种情况下,当我删除显式删除的移动构造/分配方法时,代码编译.AFAIK在声明复制赋值/构造方法时,编译器不会隐式声明相应的移动成员.所以它们仍应被有效删除,对吧?当我删除move construct/assign的显式删除时,为什么代码会编译?
一般来说,这个C++ 11缺陷有什么好的解决方法?我不希望我的物体可以移动(但它们是可复制的).