为什么这段代码不能编译?我本以为会选择内置的一元运算符&,这样两个二元运算符& 之间的歧义就不重要了。如果注释掉其中一个二元运算符&,则代码将编译(使用 gcc 11.2)并选择内置一元运算符&。
struct A
{ int operator&(int) const { return 1; }
};
struct B
{ int operator&(int) const { return 2; }
};
struct C : A, B
{};
C* test(C& c)
{ return &c; } //error: request for member 'operator&' is ambiguous
Run Code Online (Sandbox Code Playgroud) 我试图了解 C++20 中引入的新默认比较运算符。我的问题是关于何时隐式定义显式默认的比较运算符。下面的代码示例说明了这个问题:
#include <iostream>
struct B
{
operator bool() const { return true; }
};
struct D : B
{
bool operator==(const D&) const = default;
};
bool operator==(B, B) { return false; }
int main ()
{ D d;
std::cout << (d == d);
}
/* Outputs:
0 in gcc 10.1
1 in msvc 19.26
*/
Run Code Online (Sandbox Code Playgroud)
该程序的输出依赖于编译器。似乎 MSVC 在遇到默认声明时为类 D 定义了 operator==,因此它不使用稍后为类 B 定义的 operator==。相比之下,gcc 等待 D 的隐式定义operator== 直到实际需要它,此时为 B 定义的 operator== 在范围内,并被使用。哪种行为(如果有)是正确的?
一个相关的问题是,为什么不能为具有引用成员的类声明默认的 operator== ?我可以看到引用成员可能会对 MSVC 方法造成问题,因为当遇到 …
为什么以下 CTAD 尝试无法编译?
template <typename T> struct C { C(T,T) {} };
template <> struct C<int> { C(int) {} };
C c(1); //error: template argument deduction failure
Run Code Online (Sandbox Code Playgroud)
我本以为构造函数 C(int) 会被推导出来。
c++ template-specialization template-argument-deduction ctad
我有一个涉及不同类类型的对象的应用程序.对象由指针引用.空指针表示关联的对象不存在.目前,调用代码很麻烦,因为每次使用指向对象的指针时,它都会测试指针值为null,并采取一些适当的操作,它为null.因为在不存在的情况下要采取的默认操作取决于对象的类型,我宁愿在对象本身的类中而不是在调用程序中对其进行编码.这导致如下构造:
class C
{ ...
void member_func() //non-virtual !
{ if (this) { do something with the object ... }
else { take some default action }
}
...
};
Run Code Online (Sandbox Code Playgroud)
显然,成员函数不能是虚拟的,因为当对象不存在时查找表不存在,并且虚拟调用将失败.但这个代码是否适用于非虚拟成员函数的合法C++?它似乎对我尝试过的编译器工作正常,但我担心可能的不可移植性.在标准中,我找不到明确允许或明确禁止此类结构的条款.
我正在尝试确定C++函数是否安全返回具有构造函数和析构函数的对象.我对标准的理解是它应该是可能的,但我用简单的例子进行的测试表明它可能有问题.例如以下程序:
#include <iostream>
using namespace std;
struct My
{ My() { cout << "My constructor " << endl; }
~My() { cout << "My destructor " << endl; }
};
My function() { My my; cout << "My function" << endl; return my; }
int main()
{ My my = function();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出输出:
My constructor
My function
My destructor
My destructor
Run Code Online (Sandbox Code Playgroud)
在MSVC++上编译时,但使用gcc编译时会得到以下输出:
My constructor
My function
My destructor
Run Code Online (Sandbox Code Playgroud)
这是"未定义的行为"的情况,还是一个不按标准方式运行的编译器?如果是后者,哪个?gcc输出更接近我的预期.
到目前为止,我一直在设计我的类,假设每个构造函数调用最多只有一个析构函数调用,但是这个例子似乎表明这个假设并不总是成立,并且可能依赖于编译器.标准中是否有任何内容指定此处应该发生什么,或者最好避免函数返回非平凡对象?如果这个问题是重复的,请道歉.
c++ ×5
c++20 ×1
constructor ×1
ctad ×1
default ×1
destructor ×1
null ×1
template-argument-deduction ×1
this ×1