开发者

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

I have the following constructor:

 TCPConnector(int32_t fd, string ip, uint16_t port,
            vector<uint32_t>&开发者_StackOverflow社区amp; 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?


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) ...


std:;string has a default constructor which will be used to construct _ip (assuming it is a string). You can then safely assign to it. However, using an initialisation list is better practice:

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 )
{
}

This uses copy construction to create objects like _ip, rather than default construction and then assignment. This is more efficient, and is required by classes that don't support default construction but do provide other constructors, such as the copy constructor.


Well, it is safe, just inefficient. The compiler will generate a call to the default constructor. Write it like this instead to avoid that:

TCPConnector(/* etc... */)
    : IOHandler(fd, IOHT_TCP_CONNECTOR), _id(id) 
{
  // the rest of them
}


Sure, why not?

Yes, occasionally, you'll run upon a class which has special allocation requirements. Those do not end of as basic types in the Standard.


Yes. In your code above _ip will be default-constructed, then use the assignment operator to assign a new string to it, ip. If you initialize _ip in the initializer list then you save the default-construction of the string, which will save a function call and probably a heap allocation. The initializers in the initializer-list are processed in the order the members were declared in the class declaration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜