gpt4 book ai didi

c++ - Visual Studio 2015 中的返回值优化?

转载 作者:可可西里 更新时间:2023-11-01 15:48:33 24 4
gpt4 key购买 nike

在一个项目中我使用了类似下面的代码:

class C {
public:
C() {}

C(const C&) = delete;
};

C f() {
return C();
}

int main() {
f();
}

在我以前使用的每个 Visual C++ 编译器中(直到 2013 年),这从来都不是问题。但是,当我尝试使用新的 Visual C++ 2015 编译器对其进行编译时,出现以下错误:

1>c:\devel\c++11\playground\main.cpp(10): error C2280: 'C::C(const C &)': attempting to reference a deleted function
1> c:\devel\c++11\playground\main.cpp(6): note: see declaration of 'C::C'

我不确定它以前为什么有效,但我假设由于返回值优化,调用了默认构造函数而不是复制构造函数。

我使用的代码是合法的 C++ 吗?如果不是,那么在不需要我的类 C 的复制构造函数的情况下实现此代码的正确方法是什么?我当然可以使用移动构造函数,但我假设代码在 C++11 之前永远不会是有效的 C++?

最佳答案

函数参数和返回值使用 copy-initialization 初始化. 复制初始化 要求复制构造函数可访问,即使它们被 (N)RVO 省略:

If T is a class type, and the type of other is different, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type derived from T if T is a class type and a conversion function is available) are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary if a converting constructor was used, is then used to direct-initialize the object. The last step is usually optimized out and the result of the conversion is constructed directly in the memory allocated for the target object, but the appropriate constructor (move or copy) is required to be accessible even though it's not used.

关于c++ - Visual Studio 2015 中的返回值优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31539597/

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