gpt4 book ai didi

c++ - 存在用户定义的析构函数时如何禁用隐式定义的复制构造函数生成

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:27 25 4
gpt4 key购买 nike

是否有任何编译器标志来执行下一个规则?

The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

The generation of the implicitly-defined copy assignment operator is deprecated(since C++11) if T has a user-declared destructor or user-declared copy constructor.

我有兴趣在任何 Clang、Visual Studio 2013 或 GCC 中执行规则,因为代码库将与所有这些一起编译。

最佳答案

bug report提到这个在 gcc 中不发出警告的测试用例:

struct W {
int a;
~W() { a = 9; }
};

int main() {
W w {};
W v = w;
}

引用Johnathan Wakely的评论:

That's not true, the compiler can (and does) warn about legal code.

I'm confirming this, we will want the warning at some point, and it would allow us to improve this part of the -Weffc++ warnings:

* Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory.

(see PR 16166 for more details)

Maybe we could call this warning -Wdeprecated-special-members, and have it enabled -Weffc++ and in C++11 also by -Wdeprecated

Clang 已经通过 -Wdeprecated 对此发出警告:

main.cpp:3:3: warning: definition of implicit copy constructor for 'W' is deprecated because it has a user-declared destructor [-Wdeprecated]

~W() { a = 9; }

^

main.cpp:8:8: note: implicit copy constructor for 'W' first required here

W v = w;

Microsoft明确指出 Visual Studio 在这种情况下不会发出警告:

Additionally, the C++11 standard specifies the following additional rules:

  • If a copy constructor or destructor is explicitly declared, then automatic generation of the copy-assignment operator is deprecated.

  • If a copy-assignment operator or destructor is explicitly declared, then automatic generation of the copy constructor is deprecated.

In both cases, Visual Studio continues to automatically generate the necessary functions implicitly, and does not emit a warning.

关于c++ - 存在用户定义的析构函数时如何禁用隐式定义的复制构造函数生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26253652/

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