gpt4 book ai didi

c++ - 使用 "Uncopyable"类时静音 GCC 警告

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:28 25 4
gpt4 key购买 nike

我有几个类不想被复制,其中一些类有指针数据成员。为了使这些类不可复制,我私下继承了以下类模板:

template <class T>
class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
T & operator=(const T&);
};

我是这样使用的:

class Entity : private Uncopyable<Entity> { }

这工作正常,但是当我使用 -Weffc++ 编译时,我仍然收到以下警告:

class Entity has pointer data members
but does not override Entity(const Entity&)
or operator=(const Entity&)

为什么它仍然给我这个警告?

最佳答案

C++ 说

Because a copy assignment operator is implicitly declared for a class if not declared by the user, a base class copy assignment operator is always hidden by the copy assignment operator of a derived class (13.5.3). A using-declaration (7.3.3) that brings in from a base class an assignment operator with a parameter type that could be that of a copy-assignment operator for the derived class is not considered an explicit declaration of a copy-assignment operator and does not suppress the implicit declaration of the derived class copy-assignment operator; the operator introduced by the using-declaration is hidden by the implicitly-declared copy-assignment operator in the derived class.

代码中的错误是您的基类声明 operator= 以接受派生类类型的引用。这不会阻止 operator= 为基础隐式公开声明。因此,您的派生类您的基类仍然是可分配的。尝试将不可复制的类更改为非模板,这就足够了:

class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const Uncopyable &);
Uncopyable & operator=(const Uncopyable&);
};

还有一件事我刚刚在该代码中想到:不要将 Uncopyable 的析构函数设为虚拟。原因是,没有人(除了派生类本身)可以在指向 Uncopyable 的指针上调用 delete(因为 1:析构函数是 protected ,2:你是私有(private)派生的)。因此,使派生类的析构函数隐式虚拟化不是 Uncopyable 的关注点。如果派生类需要有一个虚析构函数,把 virtual 放在那里,并让 Uncopyables 的析构函数为非虚函数。

关于c++ - 使用 "Uncopyable"类时静音 GCC 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/394854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com