Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a std::string be assigned within a constructor?

Tags:

c++

I have the following constructor:

 TCPConnector(int32_t fd, string ip, uint16_t port,
            vector<uint32_t>& protocolChain, const Variant& customParameters)
    : IOHandler(fd, IOHT_TCP_CONNECTOR) {
        _ip = ip;
        _port = port;
        _protocolChain = protocolChain;
        _closeSocket = true;
        _customParameters = customParameters;
    }

And I wanted to know whether or not a string (i.e. _ip) can be assigned safely within the constructor without explicitly initializing it?

like image 933
bbazso Avatar asked Dec 22 '22 05:12

bbazso


1 Answers

std::string has several constructors. In your case, it's default constructed (to ""), then is assigned a new value.

Consider placing it (and your other variables) into the initialization list:

: _ip(ip) ...
like image 141
GManNickG Avatar answered Jan 07 '23 16:01

GManNickG