gpt4 book ai didi

c++ - 为什么来自 IBM XL C/C++ 编译器的警告?

转载 作者:可可西里 更新时间:2023-11-01 17:36:27 26 4
gpt4 key购买 nike

下面是说明问题的最小代码示例:

#include <iostream>

class Thing
{
// Non-copyable
Thing(const Thing&);
Thing& operator=(const Thing&);

int n_;

public:
Thing(int n) : n_(n) {}

int getValue() const { return n_;}
};

void show(const Thing& t)
{
std::cout << t.getValue() << std::endl;
}

int main()
{
show(3);
}

这会产生同样的错误:

int main()
{
show( Thing(3) );
}

AIX 下的 IBM XL C/C++ 8.0 编译器发出以下警告:

"testWarning.cpp", line 24.9: 1540-0306 (W) The "private" copy constructor "Thing(const Thing &)" cannot be accessed.
"testWarning.cpp", line 24.9: 1540-0308 (I) The semantics specify that a temporary object must be constructed.
"testWarning.cpp", line 24.9: 1540-0309 (I) The temporary is not constructed, but the copy constructor must be accessible.

我还尝试了带有“-Wall”和“-pedantic”的 g++ 4.1.2,但没有得到任何诊断。为什么这里需要访问复制构造函数?除了使对象可复制(这在我的控制范围之外)或进行显式复制以传递(当实际对象的复制成本很高时)之外,我如何才能消除警告?

最佳答案

相关规则在标准的 §8.5.3/5 中。确定了三种基本情况。第一个涉及初始化程序(在您的情况下为“3”)是左值或具有类类型。由于这些都不是真的,所以您拥有的是第三种情况:使用没有类类型的右值初始化 const 引用。 8.5.3/5 中的最后一个项目符号涵盖了这种情况:

Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cv-qualification than, cv2; otherwise, the program is ill-formed.

编辑:重读,我认为 IBM 是对的。我之前考虑过必须复制临时文件的可能性,但这不是问题的根源。要使用 §8.5 中指定的非引用复制初始化来创建临时文件,它需要复制构造函数。特别是,在这一点上它等同于这样的表达式:

T x = a;

这基本上等同于:

T x = T(a);

即需要创建一个临时对象,然后将临时对象复制到正在初始化的对象(在本例中,也是一个临时对象)。总结所需的过程,它大致相当于如下代码:

T temp1(3);
T temp2(temp1); // requires copy ctor
show(temp2); // show's reference parameter binds directly to temp2

关于c++ - 为什么来自 IBM XL C/C++ 编译器的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1615660/

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