其他分享
首页 > 其他分享> > c – 禁止复制构造函数,但允许其他类型的隐式复制

c – 禁止复制构造函数,但允许其他类型的隐式复制

作者:互联网

这是我的代码,我禁用了复制构造函数,但它也禁用了其他类型的隐式副本.在这种情况下的任何解决方法?

测试: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&&) = 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.

源类型是项目,目标类型是test,它是复制初始化,因此它属于第二个项目符号点.使用test(const item& a)构造函数只有一个可用的转换,因此从该项构造一个prvalue临时类型test,然后用于根据第一个项目符号点直接初始化目标.反过来,这必须调用一个可以接受const测试的测试构造函数.或测试&&论点.即使复制或移动被省略,您仍然必须具有这样的构造函数.

标签:c,c11,class,copy-constructor
来源: https://codeday.me/bug/20190830/1768760.html