简体   繁体   中英

How to copy a cstring to a member variable in a constructors initializer list?

Instead of doing it this way:

myClass::myClass(char* name) :
    name(nullptr)
{
this->name = new char[strlen(name) + 1];
    strcpy(this->name, name);
}

How can I initialize name completely inside of the initializer list?

Since we're dealing with exercises in futility:

myClass::myClass(char* name): name_{
  [](char* n) {
    auto ret = new char[strlen(n) + 1]; 
    strcpy(ret, n);
    return ret;
  }(name)
} {}

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