简体   繁体   中英

C struct copy in C++ constructor initialization list

My problem is with the following code:

extern "C" struct CStruct {
  char a;
  char b;
};

class X {
  CStruct cs;

public:
  X(CStruct cs_arg) : cs{cs_arg} {}
  X(CStruct cs, bool){
    this->cs = cs;
  }

};

Clang 3.4 (c++11) complains for the first constructor but not for the second one.

../st2.cpp:10:25: error: no viable conversion from 'CStruct' to 'char'
        X(CStruct cs_arg) : cs{cs_arg} {}
                               ^~~~~~
1 error generated.

How come it says conversion to char if the cs member is clearly a struct? Can i make this kind of initalization work in the initialization list or must i do it in the function body? Why?

The real code uses a template for the class and it fails if the type is a simple POD struct. It should never handle anything more complex then POD structs.

You are using aggregate initialization.

You should have

cs {char1, char2} .

If you want initialiation from another struct, you should use

cs(cs_arg). 

Or, if you don't want to make a copy constructor use

cs{cs_arg.a, cs_arg.b};

Are you trying to initialize cs? Then the code may be corrected like

  X(CStruct cs_arg) : cs(cs_arg) {}             // change cs_arg{cs} to cs(cs_arg)

Here the copy constructor will be invoked.

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