简体   繁体   中英

std::string.npos validity

Was std::string.npos ever valid? (As opposed to the correct std::string::npos .)

I am seeing it a lot in an old project I'm working on, and it does not compile with VS2010.

Is it something from the pre-standard days?

Once upon a time, when C with classes was developed, the :: syntax had not yet been invented. The code looked like:

class X {
public:
    void f();
};

void X.f() // a dot! see D&E 2.3
{ 
}

However, std namespace didn't exist those days. Therefore, I suspect std::string.npos is purely Microsoft's extension (or a bug?). It might be inspired by the old syntax, and might be not.

Access to any static member via class name and dot was unfortunately allowed by prior versions of MSVC.

#include <iostream>
struct A
{
    static int a; 
};
int A::a;
int main()
{
    std::cout << A.a;
}

This code is happily accepted by MSVC9.0 with a warning

Warning 1 warning C4832: token '.' is illegal after UDT 'A'

The C++ standard obviously disallows access to a static member via className.memberName (although it is perfectly legal to access a static member via an object object.staticMemberName ).

My common sense tells me that if MSVC is aware that this is not standard and gives a warning, then we can turn that extension off. We go to Project Propertied -> C/C++ -> Language and set Disable Language Extensions to Yes . Do you think anything changes? Of course not, the compiler still accepts the illegal code with the same warning. I sometimes wonder what Disable Language Extensions actually does...

No, std::string.npos was never valid, and no, it's not something from the pre-standard days.

I see other answers mentioning that MSVC has allowed that notation.

However, MSVC is not a very compliant compiler. For example, it lets you freely bind a temporary to a reference to non- const . For another example, for Windows GUI subsystem applications you have to use not well-documented switches to make it accept a standard main . Much has improved since Microsoft hired Herb Sutter (and other guy that I don't remember the name of right now) to fix up their monstrous compiler. And in relative terms it has been really great, but in absolute terms, well that compiler is still a bit lacking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM