简体   繁体   中英

How to allocate memory to const char* class member in member initialization list

How to allocate memory to const char* class member in member initialization list?

class A {
    const char *member;
public: 
    A(const char *m);
}

A::A(const char *m):member(m) {
//I want to allocate memory to member in member initialization list
}

Try the following

class A 
{ 
    const char *member; 
public: 
    A(const char *m); 
};

A::A(const char *m) : member( new char[std::strlen( m ) + 1] ) 
{ 
    std::strcpy( member, m );
}

Take into account that the data member member is not a constant itself.

Or you can even write the following way

#include <iostream>
#include <cstring>

struct A
{
    const char *s;
    A( const char *s ) : s( std::strcpy( new char[std::strlen( s ) + 1], s ) )
    {
    }

    ~A() 
    { 
        delete [] s;
    }       
};

int main()
{
    A a( "Hello, World!" );

    std::cout << a.s << std::endl;

    return 0;
}

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