开发者

type-safety by using the ellipsis notation

开发者 https://www.devze.com 2023-01-14 13:31 出处:网络
it had been several times discussedin other subjects that it is not recommended to use variadic function because the compiler can\'t check the type of provided arguments.

it had been several times discussed in other subjects that it is not recommended to use variadic function because the compiler can't check the type of provided arguments.

But what about if the user knows exactly the type can be e.g. std::string. Could anything still go wrong here t开发者_Go百科oo?

regards


You may only pass "plain old data" (POD) types as variadic arguments. These are basic types (including pointers), and simple aggregates of other POD types; anything with non-trivial constructors, destructor, base classes or virtual functions are not POD. Passing a non-POD type gives undefined behaviour.

If you really want to use variadic functions in conjunction with complex types, you will have to pass them by pointer.

UPDATE: The C++0x draft relaxes "undefined behaviour" to "conditionally-supported, with implementation-defined semantics". I'm assuming this means you'll either get correct runtime behaviour (using the copy constructor/destructor where necessary), or a compile error, but never incorrect runtime behaviour from a conforming implementation.


The point is, even if you know what the types will be, one day, you'll pass the wrong type and the compiler won't tell you and you'll get a weird error.

If someone else joins the project, they may not be aware of any restrictions on the parameter types.

Also, if you're using an editor that does autocompletion / intellisense, it won't help you as it won't know the valid types.


As others have pointed out, ellipsis is C baggage and does not play nice with C++ concepts, such as non-trivial copy constructors.

C++0x has a safer alternative in more recent compilers (e.g. GCC 4.5), variadic templates.


If you know what type up front and templated version of your function should be able to give you the flexibility you need and guarantee type safety.

0

精彩评论

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