Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

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?

Upvotes: 5

Views: 1366

Answers (3)

Yakov Galka
Yakov Galka

Reputation: 72529

The C with classes syntax for naming a class member was, in fact, a dot:

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

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

However, the :: syntax had not yet been invented. The std namespace didn't exist yet either. Thus the std::string.npos wasn't ever valid as either C with classes or standard C++.

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.

Upvotes: 6

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

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.

Upvotes: 3

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133082

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...

Upvotes: 3

Related Questions