Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++11 standard containers "final"?

Tags:

c++

std

c++11

stl

We (should) know that C++ standard library containers, including std::string, are not meant to be inherited from. But still, C++98/03 did allow us to do it even if it was leading to bugs.

Now that the final keyword is available, are those standard library container marked final to prevent bad use of inheritance with them?

If not, why is that?

like image 615
Klaim Avatar asked Feb 15 '12 17:02

Klaim


2 Answers

The LWG discussed this issue at the recent meeting in Kona Feb. 6-10, 2012. This is LWG issue 2113.

The LWG decided to mark LWG 2113 as NAD (not a defect), with the rationale that the standard is already clear that existing classes such as containers and std::string can not be marked final by the implementation.

The discussion included the fact that while it may be frowned on to derive from such classes, it is clearly legal to do so in C++98/03. And making it illegal in C++11 would break far too much code.

Update

At this time, no library types in the current working draft are marked final.

like image 53
Howard Hinnant Avatar answered Nov 10 '22 05:11

Howard Hinnant


std::string does not seem to be marked final, nor do the other containers.

My guess as to why would be that even though deriving from them isn't generally recommended, nobody was quite sure how much working code would break if it was prohibited.

Also note that, for what it's worth, final isn't technically a key word -- it's an identifier to which a special meaning is attached, but only under specific circumstances. Code that contained something like int final; final = 1; will still work. This is mostly for backward compatibility though -- at least in new code, it's almost certainly better to use final only for the special meaning, not as a normal identifier.

like image 2
Jerry Coffin Avatar answered Nov 10 '22 05:11

Jerry Coffin