Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

c++ - When do casts call the constructor of the new type?

What are the rules to determine whether or not a particular static_cast will call a class's constructor? How about c style/functional style casts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A constructor for a class type is called whenever a new instance of that type is created. If a cast creates a new object of that class type then a constructor is called. Overload resolution determines which of the constructors for a class type are called given particular arguments.

If the target type of a static_cast is a class type, it will create a new object of the target type.

A const_cast, dynamic_cast, or reinterpret_cast will never create a new class-type object, and thus will never call a constructor.

Since a C-style cast always performs some combination of static_cast, const_cast, and reinterpret_cast, it will create a new object in the same circumstances that a static_cast would create a new object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...