gpt4 book ai didi

c++ - 使用显式构造函数返回不可复制的不可移动对象

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

如果我们有一个带有非显式构造函数的不可移动、不可复制的类,我们可以返回它并按如下方式使用(在 C++11 中):

#include <iostream>
class NonCop
{
public:
/*non explicit*/ NonCop(int a, int b) : number(a + b) {}
NonCop(const NonCop&) = delete;
int number;
};

NonCop get_non_cop()
{
return {1, 2};
}

int main()
{
NonCop &&nc = get_non_cop();
std::cout << "three: " << nc.number << std::endl;
return 0;
}

但是,如果构造函数是显式的,它就不起作用。在 C++11/C++14 中是否有任何方法可以在不修改 NonCop 的情况下执行此操作?

目前我正在使用从 NonCop 派生的变通方法,并使用包装器“去显式”构造函数,但它看起来不是很漂亮。

最佳答案

不,这是不可能的。在 C++11 或 14 中没有隐式移动或复制(编译器肯定会省略)的函数返回时,没有调用显式构造函数的机制。

在 C++17 中,您只需输入 return NonCop(1,2);并且由于“保证省略”,它将不再需要移动或复制构造函数。


但这是 C++,所以是的,我可以让您的代码以零额外开销运行。通过作弊并返回不同的类型。

template<class T>
struct implicit_construct:T {
template<class...Ts>
implicit_construct(Ts&&...ts):
T(std::forward<Ts>(ts)...) // note: this is an EXPLICIT construction
{}
};

implicit_construct<NonCop> get_non_cop()
{
return {1, 2};
}

Live example .

implicit_construct<NonCop>源自 NonCop ,因此您可以将返回值存储在 NonCop&& 中.


如果你正在写 NonCop你自己,那么我要做的是添加:

 struct explicit_construct_t {};
// ...
struct NonCop {
// ...
template<class...Ts>
NonCop( explicit_construct_t, Ts&&...ts ):
NonCop( std::forward<Ts>(ts)... )
{}
// ...
};

这意味着您可以通过在其前面加上 explicit_construct_t 来调用显式构造函数隐含地调用它们:

NonCop get_non_cop() {
return {explicit_construct_t{}, 1, 2};
}

关于c++ - 使用显式构造函数返回不可复制的不可移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42391946/

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