gpt4 book ai didi

c++ - 未物化的临时对象是否需要可访问析构函数?

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

GCC 7.2 和 Clang 5.0 不同意这种情况:

struct A;

A foo();

struct A
{
static void bar()
{
foo();
}
private:
~A()=default;
};

A foo()
{
return {};
//GCC error: A::~A() is private in this context.
};

此行为是“c++17 保证(复制省略并且与 RVO 或 NRVO 无关)”的一部分。

GCC 不编译这段代码,但 Clang 编译。哪一个是错误的?

也许这一段说机器人 Clang 和 GCC 符合标准 [class.temporary]:

When an object of class type X is passed to or returned from a function, if each copy constructor, move constructor, and destructor of X is either trivial or deleted, and X has at least one non-deleted copy or move constructor, implementations are permitted to create a temporary object to hold the function parameter or result object. The temporary object is constructed from the function argument or return value, respectively, and the function’s parameter or return object is initialized as if by using the non-deleted trivial constructor to copy the temporary (even if that constructor is inaccessible or would not be selected by overload resolution to perform a copy or move of the object). [ Note: This latitude is granted to allow objects of class type to be passed to or returned from functions in registers. — end note ]

最佳答案

我相信这是一个 clang 错误。

来自 [class.temporary] :

Temporary objects are created [...] when needed by the implementation to pass or return an object of trivially-copyable type (see below), and [...]

Even when the creation of the temporary object is unevaluated ([expr.prop]), all the semantic restrictions shall be respected as if the temporary object had been created and later destroyed. [ Note: This includes accessibility and whether it is deleted, for the constructor selected and for the destructor. However, in the special case of the operand of a decltype-specifier ([expr.call]), no temporary is introduced, so the foregoing does not apply to such a prvalue. — end note ]

foo 返回的复制初始化是一个创建临时对象的上下文,因此仍然必须遵循语义限制 - 其中包括析构函数的可访问性(正如注释所帮助说明的那样)清除)。 ~A() 必须在此上下文中可访问,但实际上不是,因此该程序应该是病式的。 gcc 拒绝是正确的。

关于c++ - 未物化的临时对象是否需要可访问析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546450/

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