理解-Weffc ++ [英] Understanding -Weffc++

查看:297
本文介绍了理解-Weffc ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

#include <string>

struct S {
    S (){}

private:
    void *ptr = nullptr;
    std::string str = "";
};

int main(){}

在GCC 4.7.1上的c $ c> -Weffc ++ 将吐出:

This, when compiled with -Weffc++ on GCC 4.7.1, will spit out:


warning: 'struct S' has pointer data members [-Weffc++]
warning:   but does not override 'S(const S&)' [-Weffc++]
warning:   or 'operator=(const S&)' [-Weffc++]

这是没有问题的,除了这个例子的一些东西:

That's no problem normally, except for a couple things with this example:


  1. 如果我注释掉任何构造函数,指针声明或字符串声明,警告消失。这是奇怪的,因为你会认为指针单独就足够了,但它不是。此外,将字符串声明更改为整数声明导致它也消失,所以它只有当它有一个字符串(或可能是其他选择类)。为什么在这些情况下警告消失?

  1. If I comment out any of the constructor, the pointer declaration, or the string declaration, the warning disappears. This is odd because you'd think the pointer alone would be enough, but it isn't. Furthermore, changing the string declaration to an integer declaration causes it to disappear as well, so it only comes up when there's a string (or probably other choice classes) with it. Why does the warning disappear under these circumstances?

通常,当所有指针都指向现有变量时OS)。没有,也没有 delete 。当类的句柄,在这些情况下,是复制,我不想要一个深层副本。我想要两个手柄指向同一个内部对象(例如像一个窗口)。有没有办法使编译器实现这一点,而不必不必要地重载复制构造函数和赋值运算符,或用 #pragma 完全禁用警告?

Often times this warning comes up when all the pointer is doing is pointing to an existing variable (most often maintained by the OS). There's no new, and no delete. When the class with the handle, in these cases, is copied, I don't want a deep copy. I want both handles to point to the same internal object (like a window, for example). Is there any way to make the compiler realize this without unnecessarily overloading the copy constructor and assignment operator, or disabling the warning completely with #pragma? Why am I being bothered in the first place when the Rule of Three doesn't even apply?


推荐答案


  1. 当你这样做时,你有一个POD结构。因为它不能有任何构造函数, -Weffc ++ 不打扰检查。

使用引用或 shared_ptr 对象或包含指针的任何其他对象。

Use a reference or shared_ptr object or any other object that wrap a pointer.

这篇关于理解-Weffc ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆