gpt4 book ai didi

c++ - 不允许复制构造函数但允许从其他类型隐式复制

转载 作者:太空狗 更新时间:2023-10-29 20:40:04 26 4
gpt4 key购买 nike

这是我的代码,我禁用了复制构造函数,但它也禁用了来自其他类型的隐式复制。在这种情况下有什么变通办法吗?

测试于:g++ (GCC) 4.7.1

struct item {
int b;
};

class test {
public:
test(const test& copy) = delete;

test(const item& a) {
std::cout << "OK " << a.b << std::endl;
}
};

int main() {
test a = item{10}; //error: use of deleted function ‘test::test(const test&)’
}

最佳答案

要么给test一个移动构造函数:

test(test&&) = default;

或者使用直接初始化:

test a{item{10}};

没有其他解决方法。目标类型是类类型的复制初始化,例如 test a = item{10};,始终需要可调用的复制或移动构造函数。


相关规则在§8.5 [dcl.init]/p17中指定:

If the destination type is a (possibly cv-qualified) class type:

  • If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.
  • Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified version of the destination type. The temporary is a prvalue. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.

源类型是item,目的类型是test,是拷贝初始化,所以属于第二点。使用 test(const item& a) 构造函数只有一个可用的转换,因此 test 类型的临时纯右值是从 item 构造的,然后用于根据第一个要点直接初始化目标。反过来,这必须调用 test 的构造函数,该构造函数可以接受 const test &test && 参数。即使省略了复制或移动,您仍然必须有这样一个可用的构造函数。

关于c++ - 不允许复制构造函数但允许从其他类型隐式复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589674/

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