gpt4 book ai didi

c++ - 避免调用默认、移动和复制构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:41 25 4
gpt4 key购买 nike

我有以下示例(扩展到 Avoid calling move constructor )

#include <cstdint>

class Interface
{
public:
Interface() = default;
virtual ~Interface() = default;
Interface(const Interface&) = delete;
Interface(Interface&&) = delete;
const Interface& operator=(const Interface&) = delete;
Interface& operator=(Interface&&) = delete;
};

class FooC : public Interface
{
public:
FooC(uint16_t iPort, uint16_t iPin)
: PORT(iPort)
, PIN(iPin)
{
};

FooC() = delete;
~FooC() override = default;
FooC(const FooC&) = delete;
FooC(FooC&&) = delete;
const FooC& operator=(const FooC&) = delete;
FooC& operator=(FooC&&) = delete;

private:
const uint16_t PORT;
const uint16_t PIN;
};

class FactoryC
{
public:
FactoryC()
: mFoo{
{1, 2},
{3, 4}
}
{
};

~FactoryC() = default;
FactoryC(const FactoryC&) = delete;
FactoryC(FactoryC&&) = delete;
const FactoryC& operator=(const FactoryC&) = delete;
FactoryC& operator=(FactoryC&&) = delete;

private:
FooC mFoo[2];
};

int main()
{
FactoryC factory{};
}

而且我不想调用默认、移动和复制构造函数。因此,我删除了这些功能。不幸的是,这会导致以下错误(使用 C++17 编译)

<source>: In constructor 'FactoryC::FactoryC()':

<source>:42:4: error: use of deleted function 'FooC::FooC(FooC&&)'

}

^

<source>:26:4: note: declared here

FooC(FooC&&) = delete;

^~~~

Compiler returned: 1

是否可以在这个例子中强制调用带有参数的构造函数,并仍然删除 FooC 的默认、移动和复制构造函数?

最佳答案

这似乎是一个错误。 @SergeyA 的评论:

This certainly looks like a bug. Making Interface destructor non-virtual (with corresponding removal of override) fixes compilation issue.

表明问题与虚拟基类有关。事实上,bug report #86849处理一个不相关的问题,Richard Smith 得出以下结论:

Interestingly, GCC does appear to suppress guaranteed copy elision if the class has virtual base classes.

关于c++ - 避免调用默认、移动和复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382501/

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