c++ - deep_const_ptr 复制构造函数

标签 c++ pointers constants smart-pointers

template <class T>
class deep_const_ptr
{
    T * priv;
public:
    deep_const_ptr(const deep_const_ptr & p_other); // copy ctor

    T const * operator->() const;
    T * operator->();
    ..... // other crap
};

void Cheese::doThings(const deep_const_ptr<Cheese> p_other)
{
    deep_const_ptr<Cheese> awayGoesTheConst(p_other); // I don't want this to work.
    awayGoesTheConst->doTerribleThings();
}

我想阻止从 const 到非 const 的复制构造。

也许这甚至没有任何意义?

新的 C++11/14/17 有可能吗?

编辑:

是的,问题是如果我不提供复制构造函数,STL 容器将无法工作。我非常需要它们来工作。

编辑:

deep_const_ptr 是我在遇到 STL 容器和 const 对象问题时想到的解决方案。

class Shape
{
    private:
        std::list<Vertex *> m_vertices;
    public:
        virtual void std::list<Vertex*> * const getVertices() { return &m_vertices; }
        virtual void std::list<Vertex const *> * const getVertices() const { return &m_vertices; } // doesn't work, cannot convert between different types of lists
}

我想从不可变形状提供不可变顶点对象。

我想到的两个解决方案是自定义 deep_const_ptr 指针类型和自定义列表,其中

Vertex const *& operator[](unsigned int) const;

最佳答案

我假设您追求的是深度常量指针实现以及如何处理它的复制。正如您已经发现的那样,一个简单的复制构造函数是行不通的,因为您只会丢失指针上的常量。没有其他方法可以禁止外部对象上的 const 删除,因此您只需要禁用复制构造函数即可。 现在你的问题的当前版本并不清楚为什么这是一个问题。根据您的评论和上一个问题,我只能推断您想要在容器中使用指针,特别是 std::vector<> 。实现这项工作的关键是禁用复制,但启用移动(请注意,您需要为此提供右值引用支持,这是 C++11 的一部分):

template <class T>
class deep_const_ptr
{
    T * priv;
public:
    deep_const_ptr(const deep_const_ptr &)  = delete; // Do not allow this!
    deep_const_ptr& operator=(const deep_const_ptr &) = delete; // Nor this!

    deep_const_ptr(deep_const_ptr &&) = default; // But this is okay
    deep_const_ptr& operator=(deep_const_ptr &&) = default; // So is this!

    T const * operator->() const;
    T * operator->();
    ..... // other crap
};

容器通常只需要移动而不是复制即可工作。

如果您确实需要支持复制,则需要对仅支持 const 访问的不同类型进行支持。例如,您可以专门化 deep_const_ptr对于 const T并且只实现 operator-> 的 const 变体和 operator*在那里。此外,您还可以通过转换运算符将 deep_const_ptr“降级”为 deep_const_ptr。但这意味着某种多所有者处理,例如引用计数,所以我将不考虑它。 const 和非 const 版本的行为不同也很奇怪,但这是您的决定。就我个人而言,我建议坚持这一举措。

关于c++ - deep_const_ptr 复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058501/

相关文章:

c - 具有成员的结构有时需要是“const”,有时不需要

objective-c - 不知道为什么出现 "EXC Bad Access"错误

c++ - Q_DECLARE_METATYPE 期望 ctor、dtor 或之前的类型转换; token

c++ - OpenGL 和 Windows 编程 C++

c++ - 带指针的函数

c++ - 当像静态变量一样访问时,类的非静态成员的地址将地址打印为 1

c - WIN32和其他c字符串的区别

c++ - 如何强制模板类型的常量性?

c++ - 如何在类中存储常量数组?

c++ - std::对象 vector ,其中封装有 boost::thread