Is it possible to assign std :: string inside the constructor?

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 if a string (i.e. _ip) can be safely assigned inside the constructor without explicit initialization?

+4
source share
5 answers

std::string has several constructors . In your case, it is configured by default (before ""), then it is assigned a new value.

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

 : _ip(ip) ... 
+7
source

std :; string has a default constructor that will be used to create _ip (assuming it's a string). Then you can safely assign it. However, using an initialization list is best 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 of type _ip, not the default, and then for assignment. This is more efficient and is required for classes that do not support the default construct but provide other constructors, such as the copy constructor.

+3
source

Well, it's safe, just ineffective. The compiler will generate a default constructor call. Instead, write this to avoid this:

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

Of course, why not?

Yes, sometimes you run a class that has special distribution requirements. Those that do not end as base types in the Standard.

0
source

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

0
source

Source: https://habr.com/ru/post/1301613/


All Articles