简体   繁体   中英

Signature of C++ copy constructor for struct with an enum

Is there a reason why the implicit copy constructor for a struct containing an enum would not use the const version - or why there is no copy-constructor at all? I would expect an implicit copy-constructor being created, ie:

X(const X& x)

I know there are rules for when this might happen, for instance if a member variable does not have a copy constructor, or a non-const copy constructor. I guess my question is how this relates to enums - and if it is this rule that applies?

Adding my own copy constructor seems to work.

Example - what, if any, copy-constructors are created implicitly:

struct MyStruct {
  int myInt;
  double myDouble; 
  MyEnum myEnum;
};

Your guess about enums is wrong; the problem is somewhere else. The following code compiles with no problem if no copy constructor is explicitly defined, and fails to compile if there is a copy constructor taking a non-const reference.

#include <iostream>
#include <iterator>
#include <vector>

enum MyEnum {
  e0, e1, e2
};

struct MyStruct {
  int myInt;
  double myDouble; 
  MyEnum myEnum;
  // MyStruct(MyStruct& ){} // uncomment to make compilation fail
};

std::ostream& operator<<(std::ostream& out, const MyStruct& s) {
  out<<"{"<<s.myInt<<","<<s.myDouble<<","<<s.myEnum<<"}";
  return out;
}

int main() {
  MyStruct s = {42, 3.1415926, e0};
  MyStruct s1 = s;
  std::vector<MyStruct> v(10, s1);
  std::copy(v.begin(), v.end(), std::ostream_iterator<MyStruct>(std::cout,"\n"));
  return 0;
}

As others pointed out in comments, a realistic example demonstrating the error is required to understand what's the real problem.

This is a little bit out of my expertise.

When you try to construct an X from a non-const lvalue instance of X , the signature X(X& ) would be a closer match, and be chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM