D
D.J. Stachniak
Hi,
I have a question about explicit constructors and the C++ standard.
Forgive me for my laziness in not pouring over the spec myself, but I
thought I'd ask first and read later. I have a class/app like so:
#include <string>
#include <iostream>
class UTF8string
{
public:
UTF8string() { }
explicit UTF8string(const char* charArray) : m_str(charArray) { }
UTF8string(const std::string& str) : m_str(str) { }
const char* c_str() { return m_str.c_str(); }
private:
std::string m_str;
};
int main(int argc, char* argv[])
{
UTF8string str = "Hello, world!";
std::cout << "str.c_str() = " << str.c_str() << std::endl;
return 0;
}
I've obviously left out a lot of irrelevant details, but what I'd like
to know is this: under VC++ 7.1 this compiles and under GCC 3.4.2 it
doesn't. GCC complains as I would expect that it can't convert "Hello,
world!" to a UTF8string object because the const char* ctor is
explicit. VC++, however, silently converts my "Hello, world!" literal
to a std::string and invokes UTF8string's const std::string& ctor.
I don't necessarily have a problem with making my const std::string&
ctor explicit as well, but I'd like to know the rules for silent
conversions like this. Who's in the right - GCC or VC++? And what are
the rules regarding the number of levels a compiler can go to find a
match?
Thanks,
D.J. Stachniak
I have a question about explicit constructors and the C++ standard.
Forgive me for my laziness in not pouring over the spec myself, but I
thought I'd ask first and read later. I have a class/app like so:
#include <string>
#include <iostream>
class UTF8string
{
public:
UTF8string() { }
explicit UTF8string(const char* charArray) : m_str(charArray) { }
UTF8string(const std::string& str) : m_str(str) { }
const char* c_str() { return m_str.c_str(); }
private:
std::string m_str;
};
int main(int argc, char* argv[])
{
UTF8string str = "Hello, world!";
std::cout << "str.c_str() = " << str.c_str() << std::endl;
return 0;
}
I've obviously left out a lot of irrelevant details, but what I'd like
to know is this: under VC++ 7.1 this compiles and under GCC 3.4.2 it
doesn't. GCC complains as I would expect that it can't convert "Hello,
world!" to a UTF8string object because the const char* ctor is
explicit. VC++, however, silently converts my "Hello, world!" literal
to a std::string and invokes UTF8string's const std::string& ctor.
I don't necessarily have a problem with making my const std::string&
ctor explicit as well, but I'd like to know the rules for silent
conversions like this. Who's in the right - GCC or VC++? And what are
the rules regarding the number of levels a compiler can go to find a
match?
Thanks,
D.J. Stachniak