C++有移动和删除语义吗?

Does C++ have move and delete semantics?

本文关键字:语义 删除 移动 C++      更新时间:2023-10-16

是否可以在C++中创建一次性变量,而无需使用大括号进行任何时髦的业务?

以下是我想要实现的示例:

const float _phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha));
const float phi       = HALF_PI - std::abs(HALF_PI - std::abs(_phiTemp));
// After running this code I want _phiTemp to be unaccessible, and the
// compiler to send an error if I ever try

这是我想要的冗长而丑陋的实现:

const float phi = 0;
{
const float _phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha));
float& phiRef = const_cast<float&> phi;
phiRef = HALF_PI - std::abs(HALF_PI - std::abs(std::move(_phiTemp)));
}
// _phiTemp is disposed and phi is a const, and safely used in the calculation
// through std::move()

我错过了什么吗?C++没有"即时"变量处置吗?

冗长而丑陋的实现也是未定义的行为;写入phiRef是对定义为 const 的变量的写入。

你能做的最好的事情就是编写一个函数来计算phi- 如果你想内联这样做,你可以写一个lambda:

const float phi = [&cluster]{
const float phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha)); 
return HALF_PI - std::abs(HALF_PI - std::abs(phiTemp));
}();

。但它仍然很丑。我认为C++不提供此功能。

Martin Bonner 走在正确的轨道上:lambda 作为"范围与return"效果很好,您可以在其中随意声明辅助变量。以下是我在个人工具包中所做的,以更进一步:

namespace initBlock_detail {
struct tag { };
template <class F>
decltype(auto) operator * (tag, F &&f) {
return std::forward<F>(f)();
}
}
#define glk_initBlock 
glk::initBlock_detail::tag{} * [&]() -> decltype(auto)

调用语法如下所示:

const float phi = glk_initBlock {
const float phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha)); 
return HALF_PI - std::abs(HALF_PI - std::abs(phiTemp));
};

我认为你想要的是一个临时变量。 即不要命名您的中间值。

const float phi = HALF_PI - std::abs(
HALF_PI - std::abs(
atan2(
tan(cluster.beta)
, tan(cluster.alpha)
)
)
);