Understanding of “inline” in C++ class constructor? [duplicate]

情到浓时终转凉″ 提交于 2019-12-12 04:14:30

问题


I read a source code of class address_v4 in boost library and there are several constructors declared with BOOST_ASIO_DECL (defined as inline)

/// Construct an address from raw bytes.
BOOST_ASIO_DECL explicit address_v4(const bytes_type& bytes);

/// Construct an address from a unsigned long in host byte order.
BOOST_ASIO_DECL explicit address_v4(unsigned long addr);

(from here http://www.boost.org/doc/libs/1_64_0/boost/asio/ip/address_v4.hpp)

# define BOOST_ASIO_DECL inline

(from here http://www.boost.org/doc/libs/1_64_0/boost/asio/detail/config.hpp)

So, what the purpose of specifing "inline" for c++ constructor ? Is it the same meaning as for functions or it has a different meaning ?


回答1:


It has exactly the same meaning (as some programmer dude noted the ctor is a function like any other) but given that any compiler (I can think of) will happily ignore your suggestion (to decide if inline is required or not using all his knowledge) then it has to have another use...

In fact it's there to define a function (or ctor) in your header file without the errors linker will raise because of the one definition rule.

Note that it opens another scenario when function has not a body: to define the function in multiple translation units. In this case each implementation must be the same (AFAIK, please correct me if I'm wrong) or it's UB.

In short: define a function in your header file and use it in multiple translation units: linker error. Mark it as inline and errors are gone (and it won't imply that function is really inlined).



来源:https://stackoverflow.com/questions/44247614/understanding-of-inline-in-c-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!