473,662 Members | 2,760 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Circumventing explicit constructors

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(cons t char* charArray) : m_str(charArray ) { }

UTF8string(cons t 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

Nov 22 '05 #1
9 1542
D.J. Stachniak wrote:
class UTF8string
{
public:
UTF8string() { }
explicit UTF8string(cons t char* charArray) : m_str(charArray ) { }
UTF8string(cons t std::string& str) : m_str(str) { } 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.
UTF8string str = "Hello, world!";


VC7.1 is incorrect here. The rhs, i.e. const char* must be converted to the type of the
lhs first, see 8.5/14. VC7.1 is known to have a problem with this type of initialisation
where it does not follow the standard, see the thread "conversion constructor called twice
- why?".

--

Valentin Samko - http://www.valentinsamko.com
Nov 22 '05 #2

D.J. Stachniak wrote:
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?


Like you, I'm too lazy to go into the spec! But, haha! Permit me the
following piece of speculation, anyway.

It must be the case that, under overload resolution, constructors are
considered without regard to their being declared explicit or not. The
candidate is chosen, and if it is explicit, a diagnostic is required.

In your program, the const char * constructor is the better match,
because it doesn't require a user-defined conversion. So it must be
chosen, and then a diagnostic is issued because the constructor is
explicit.

This is the correct design, rather than eliminating all the explicit
constructors from consideration as if they did not exist, and
considering only the remaining functions as overload candidates.

This design allows the explicit feature to be a superior diagnostic
tool. By turning on the explicit attribute on a constructor, you can
detect that it's being selected, without disturbing the logic which
makes that selection. This is analogous to access specifiers, which
don't alter any visibility rules, but merely flag certain accesses as
disallowed.

Nov 22 '05 #3

Kaz Kylheku wrote:
In your program, the const char * constructor is the better match,
because it doesn't require a user-defined conversion. So it must be
chosen, and then a diagnostic is issued because the constructor is
explicit.


IMHO, const char* constructor is the _only_ possible match. The other
constructor simply cannot match, since it will require _two_ user
defined conversions : const char[] --> std::string --> UTF8string

Please correct me if I am wrong.

Nov 22 '05 #4

"D.J. Stachniak" <dj*********@gm ail.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
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?


As the others have already mentioned, g++ is "right" in this case.

However, you will find that VC++ (7.1) too emits a compiler error in this
case when you try to compile the code with the /Za switch (which disables
extensions).

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Nov 22 '05 #5

Neelesh Bodas wrote:
Kaz Kylheku wrote:
In your program, the const char * constructor is the better match,
because it doesn't require a user-defined conversion. So it must be
chosen, and then a diagnostic is issued because the constructor is
explicit.


IMHO, const char* constructor is the _only_ possible match. The other
constructor simply cannot match, since it will require _two_ user
defined conversions : const char[] --> std::string --> UTF8string

Please correct me if I am wrong.


We are talking about the line:

UTF8string str = "Hello, world!";

In calling the const std::string & constructor, there is only one
conversion involved.

There is a second conversion going on, from std::string to UTF8String
object. But the constructor call /is/ that conversion. This second
conversion is not part of the conversion chain that must be done in
order to produce the argument for the constructor call; it's done by
that call.

Nov 22 '05 #6

Kaz Kylheku wrote:
We are talking about the line:

UTF8string str = "Hello, world!";

In calling the const std::string & constructor, there is only one
conversion involved.

There is a second conversion going on, from std::string to UTF8String
object. But the constructor call /is/ that conversion. This second
conversion is not part of the conversion chain that must be done in
order to produce the argument for the constructor call; it's done by
that call.


Hello Kaz,
Thanks for the explanation. Actually I am still a bit confused.
Suppose I comment out all other other constructors but retain this one
-

UTF8string ( const std::string& str);

Now (according to what I understand from your explanation), this
constructor should be a legal candidate for the expression :

UTF8string str = "Hello, world"; // The LHS must get constructed from
the RHS.

Howvever, this code fails to compile (g++ 3.4.2).

Further, If I make one of the two conversions explicit, then the code
works :

UTF8string str = std::String("He llo, world");
// OK, const char[] --> std:: string called explicitly, other
conversion is implicit

UTF8string str = UTFString("Hell o, world" );
// OK, std::string --> UTF8string called explicitly, other conversion
is implicit

This is precisely the reason why I believed the two-conversion issue
(and wrote the previous reply)

So basically, IMHO, when we say
X foo = bar, there _is_ a conversion from bar to some temporary of type
X, and then a call to CC to construct a foo. Of course the compilers
might optimize the CC call, but the underlying type conversion does
take place.

Of course I might be wrong and missing out some sublte points here.
Could you please comment on this?

Nov 22 '05 #7
I just found a switch for the VC compiler (/Za) that forces compliance
with standard C++. With this flag set my code above no longer compiles
under VC, so clearly GCC is correct. Thanks for everyone's help.

Nov 22 '05 #8
Neelesh Bodas wrote:
Hello Kaz,
Thanks for the explanation. Actually I am still a bit confused.
Suppose I comment out all other other constructors but retain this one
-

UTF8string ( const std::string& str);

Now (according to what I understand from your explanation), this
constructor should be a legal candidate for the expression :

UTF8string str = "Hello, world"; // The LHS must get constructed from
the RHS.

Howvever, this code fails to compile (g++ 3.4.2).


Doh, never mind: I was thinking of:

UTF8string str("Hello, world");

:)

Nov 22 '05 #9
Kaz Kylheku wrote:
Neelesh Bodas wrote:
IMHO, const char* constructor is the _only_ possible match. The other
constructor simply cannot match, since it will require _two_ user
defined conversions : const char[] --> std::string --> UTF8string


We are talking about the line:

UTF8string str = "Hello, world!";

In calling the const std::string & constructor, there is only one
conversion involved.

There is a second conversion going on, from std::string to
UTF8String object. But the constructor call /is/ that conversion.


The statement

T t = x;

is treated as

T t(( T(x) ));

if x is not of type T (I used double brackets to avoid
writing a function declaration).
So there are in fact two conversions.
The following only has one conversion though:

UTF8string str("Hello, world!");

Nov 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
7510
by: Christoph Bartoschek | last post by:
Hi, gcc 3.4 rejects the following program: class T { public: T() : a(3) {} explicit T(T const & other) : a(other.a) {} private: int a;
12
4750
by: Marcelo Pinto | last post by:
Hi all, In practice, what is the diference between a default constructor and an explicit default constructor? class Ai { public: Ai() {} };
9
2365
by: Tanmoy Bhattacharya | last post by:
Hi, This is a question about whether I am right that a particular syntactic sugar is missing in C++. Let me explain with an example. Let us say I have a class for complex numbers, and I want people to be able to initialize real numbers (like an object of type double) from it ... in such a context (or if someone explicitly casts to double), the imaginary part is to be ignored. However, I certainly do not want people to be able to ask...
2
2139
by: Dave | last post by:
Hello NG, Can anybody fathom the purpose of an explicit copy constructor? On page 232 of the Josuttis STL reference, I see a reference to such. How could you ever need to supress the possibility of an implicit conversion from type T to type T? Such an implicit conversion could never occur because you're already of the required type! Thanks,
1
2249
by: John | last post by:
Hi, Maybe someone can help me with the following: "The first task by any derived class constructor is to call it’s direct or indirect base class constructor implicitly or explicitly", reads the statement. To test this, I added messageboxes in all constructors indicating which constructor is called. There are four constructors which could be called: 1. Base class empty constructor 2. Base class 2-Par. constructor
2
3925
by: Fred Zwarts | last post by:
Consider the following code: // Start of code class MyException_t { public: // Default constructor.
1
2313
by: petschy | last post by:
hello, i've run into an error when qualifying a copy ctor 'explicit'. the strange thing is that i get a compiler error only if the class is a template and declare the variable as X<Zx = y. X<Zx(y) is fine. Tested with gcc 2.95, 3.3, 4.1, all gave the same error: t.cpp: In function 'int main()': t.cpp:44: error: no matching function for call to 'D<int>::D(D<int>&)'
42
2681
by: coder_lol | last post by:
Thanks everyone again for contributing to helping me clear C++ confusions. I did some serious reading on copy constructors and assignments and I think I've got a good handle on the memory stuff. Well, I came across Scott Meyer's SmartPtr example from some 10 years ago. I like the template member function for type conversion to solve inheritance issues. On MSVS 2003, I get the below error, if I declare the constructor SmartPtr(T*...
12
7192
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
0
8435
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.