gpt4 book ai didi

c++ - 英特尔 13.1.2 中带有已删除复制构造函数的不良 C++ 行为的解决方法

转载 作者:行者123 更新时间:2023-11-30 04:58:15 25 4
gpt4 key购买 nike

我坚持支持回到 Intel 13.1.2,它名义上是 C++11 兼容的,但是这段代码:

#include <algorithm>

struct moveonly {
moveonly() =default;
moveonly(const moveonly&) =delete;
moveonly(moveonly&& other) { member = std::move(other.member); }

private:
int member = 0;
};

template <typename T>
struct holds {
operator T&&() { return std::move(t); }
T t;
};


int main() {
holds<moveonly> m;
moveonly a = m;
}

编译失败:

 ╰─▸ icc -std=c++11 test.cc -o test
test.cc(21): error: function "moveonly::moveonly(const moveonly &)" (declared at line 5) cannot be referenced -- it is a deleted function
moveonly a = m;
^

test.cc(21): error: function "moveonly::moveonly(const moveonly &)" (declared at line 5) cannot be referenced -- it is a deleted function
moveonly a = m;
^

compilation aborted for test.cc (code 2)

假设我无法使类可复制,并且想保留转换运算符,有人能想出解决方法吗?

最佳答案

您可以尝试使右值显式化:

moveonly a = std::move(m);

可能,显式转换也有帮助:

moveonly a = static_cast<moveonly&&>(m);

显式调用转换运算符:

moveonly a = m.operator moveonly&&();

如果都失败了,回到 C++11 之前的版本意味着:

struct holds
{
operator T&&() { return std::move(t); }
T t;
swap(T& tt)
{
swap(t, tt);
}
};

为 moveonly 定义了适当的交换,这样你就可以:

moveonly a;
m.swap(a);

关于c++ - 英特尔 13.1.2 中带有已删除复制构造函数的不良 C++ 行为的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51754610/

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