With the following code, if I attempt to convert a template array to std::string, instead of the compiler using the expected std::string conversion method, it raises an ambiguity resolution problem (as it attempts to call the array conversion methods):
#include <iostream>
template<typename TemplateItem>
class TestA
{
public:
TemplateItem Array[10];
operator const TemplateItem *() const {return Array;}
operator const std::string() const;
};
template<>
TestA<char>::operator const std::string() const
{
std::string Temp("");
return Temp;
}
int main()
{
TestA<char> Test2;
std::string Temp("Empty");
Temp = Test2; //Ambiguity error. std::string or TemplateItem * ?
return 0;
}
What modification do I need to make to the code in order to make it so the code correctly and implicitly resolve to the std::string conversion function? Especially given the const TemplateItem * would be treated as a null-terminated array (which it won't likely be).
First, the reason you have ambiguity: you provide both conversion to char* and conversion to std::string const, and std::string likes them both.
By the way, before getting to your question, the const in operator std::string const was once a good idea, advocated by e.g. Scott Meyers, but is nowadays ungood: it prevents efficient moving.
Anyway, re the question, just avoid implicit conversions. Make those conversions explicit. Now I answered that in response to another SO question, and someone (I believe the person was trolling) commented that C++98 doesn't support explicit type conversion operators. Which was true enough, technically, but pretty stupid as a technical comment. Because you don't need to use the explicit keyword (supported by C++11), and indeed that's not a good way to make the conversions explicit. Instead just name those conversions: use named member functions, not conversion operators.
#include <iostream>
template<typename TemplateItem>
class TestA
{
public:
TemplateItem Array[10];
TemplateItem const* data() const { return Array; }
std::string str() const;
};
template<>
std::string TestA<char>::str() const
{
return "";
}
int main()
{
TestA<char> test2;
std::string temp( "Empty" );
temp = test2.str(); // OK.
temp = test2.data(); // Also OK.
}
Cheers & hth.
I will add, after thinking about it, here's the reasoning and what should be done:
The operator const TemplateItem *(); Should be deleted.
Why? There never will be an instance where you would want implicit conversion of TestA (or any template class) to a TemplateItem array with an unknown size - because this has absolutely no bounds checking (array could be sizeof 1 or 10 or 1000 or 0) and would likely cause a crash if a calling function or class received the array with no idea what size it is.
If the array is needed, either use the operator[] for direct items, or GetArray (which would signal the user intends to pass an unknown-length array).
Retain operator const std::string. Code will compile. Possible memory issues down the line averted.
(Alf for his efforts has been selected as the 'correct' answer, although this is the more logical option)
Related
I am writing a code in C++ right now, and I have a dilemma.
EDIT: I added the class relevant definition
_fullName is defined in the class as a private dm(char _fullName)
my class contains the getter method below:
char* getFullName() const { return this->_fullName; }
However, I had in the past cases in which I returned char* with const(const char*)
I can change the getter method to this one:
const char* getFullName() const { return this->_fullName; }
Both versions are compiling but I don't know how to choose.
I would take the second version, but I wonder Why even the version without the const is compiling? shouldn't it give an error when I remove the const keyword, because the function is a CONST member function and therefore the dms are const as well and cannot be returned without the const keyword???
This is the class relevant definition:
class Professional
{
private:
char* _ID;
char* _fullName;
int _age;
char* _profession;
}
First understand what const attached to a member function means. It determines the const-ness of the implicit this used for the member. Given this:
struct S
{
char value[10];
const char *mfn() const { return value; }
};
within the confines of mfn the implicit this is const S *. Furthermore, all references to members obtained therein are also const. In this case, that means value as an expression representation is const char (&)[10] before any further conversion are attached therein.
That's important.
In the correct posted example above there is an automatic conversion to temporary pointer, since const char(&)[10] converts to const char* without objection. However, the following will fail:
struct S
{
char value[10];
char *mfn() const { return value; }
};
The reason this will fail is simply because there is no conversion possible. value, remember, is const char (&)[10], and can only implicitly convert to const char*.
But how could it succeed? Well, consider this:
struct S
{
char *ptr;
char *mfn() const { return ptr; }
};
This will work. The reason is subtle, but obvious once you think about it. ptr is a char*. The attachment of const to this makes that char * const&, not const char *& (there is a difference; the former is a reference to a non-mutable pointer to mutable data, the latter is a reference to a mutable pointer to non-mutable data). Since return ptr is not mutating ptr (or anything else in the object), it is viable as a result.
In short, in your case it works because the pointer you are returning isn't via some implicit conversion from a const underlayment; it's just a value.
You have a few things going on here, in your example of the int num member this is not the same as a char * member.
lets expand your example a bit:
class Professional
{
int* func() const
{
return &myInt; // Fails because it returns a reference to a member variable
}
char* func() const
{
return &myChar; // Fails because it returns a reference to a member variable
}
int* func() const
{
return pInt; // ok because it returns a COPY of the member pointer
}
char* func() const
{
return pChar; // ok because it returns a COPY of the member pointer
}
int myInt;
char myChar;
int *pInt;
char *pChar;
Note: the two pointers getting returned by copy are ok. Its the pointers that are copies not the thing being pointed to. The memory that is pointed to is nothing to do with this class.
As to an answer to your question: there is a rule of thumb that is to apply const as much as possible - this helps to show other users your intent and gains benefits from compiler warnings / errors if a user tries to use your class in a way you did not intend. So in this case pass back a const char *.
Note: See this answer for more specific details here: What is the difference between const int*, const int * const, and int const *?
I like to know pro's and con's for having and not-having such cast. At several places including here on Stack Overflow I can see that the const char* cast is considered bad idea but I am not sure why?
Lack of the (const char*) and forcing to always use c_str() cast creates some problems when writing generic routines and templates.
void CheckStr(const char* s)
{
}
int main()
{
std::string s = "Hello World!";
// all below will not compile with
// Error: No suitable conversion function from "std::string" to "const char *" exists!
//CheckStr(s);
//CheckStr((const char*)s);
// strlen(s);
// the only way that works
CheckStr(s.c_str());
size_t n = strlen(s.c_str());
return 0;
}
For example, if I have a large number of text processing functions that accept const char* as input and I want to be able to use std::string each time I have to use c_str(). But in this way a template function can't be used for both std::string and const char* without additional efforts.
As a problem I can see some operator overloading issues but these are possible to solve.
For example, as [eerorika] pointed, with allowing implicit cast to pointer we are allowing involuntary the string class to be involved in boolean expressions. But we can easily solve this with deleting the bool operator. Even further, the cast operator can be forced to be explicit:
class String
{
public:
String() {}
String(const char* s) { m_str = s; }
const char* str() const { return m_str.c_str(); }
char* str() { return &m_str[0]; }
char operator[](int pos) const { return m_str[pos]; }
char& operator[](int pos) { return m_str[pos]; }
explicit operator const char*() const { return str(); } // cast operator
operator bool() const = delete;
protected:
std::string m_str;
};
int main()
{
String s = "Hello";
string s2 = "Hello";
if(s) // will not compile: it is a deleted function
{
cout << "Bool is allowed " << endl;
}
CheckStr((const char*)s);
return 0;
}
I like to know pro's and con's for having and not-having such cast.
Con: Implicit conversions often have behaviour that is surprising to the programmer.
For example, what would you expect from following program?
std::string some_string = "";
if (some_string)
std::cout << "true";
else
std::cout << "false";
Should the program be ill-formed because std::string is has no conversion to bool? Should the result depend on the content of the string? Would most programmers have the same expectation?
With the current std::string, the above would be ill-formed because there is no such conversion. This is good. Whatever the programmer expected, they'll find out their misunderstanding when they attempt to compile.
If std::string had a conversion to a pointer, then there would also be a conversion sequence to bool through the conversion to pointer. The above program would be well-formed. And the program would print true regardless of the content of the string, since c_str is never null. What if programmer instead expected that empty string would be false? What if they never intended either behaviour, but used a string there by accident?
What about the following program?
std::string some_string = "";
std::cout << some_string + 42;
Would you expect the program to be ill-formed because there is no such operator for string and int?
If there was implicit conversion to char*, the above would have undefined behaviour because it does pointer arithmetic and accesses the string buffer outside of its bounds.
// all below will not compile with
strlen(s);
This is actually a good thing. Most of the time, you don't want to call strlen(s). Usually, you should use s.size() because it is asymptotically faster. The need for strlen(s.c_str()) is so rare, that the little bit of verbosity is insignificant.
Forcing the use of .c_str() is great because it shows the reader of the program that it is not a std::string that is passed to the function / operator, but a char*. With implicit conversion, it is not possible to distinguish one from the other.
... creates some problems when writing generic routines and templates.
Such problems are not insurmountable.
If by "having a cast" you mean a user defined conversion operator, then the reason it does not have it is: to prevent you from using it implicitly, possibly inadvertently.
Historically, unpleasant consequences of an inadvertent use of such conversion stem the fact that in the original std::string (per C++98 specification) the operation was heavy and dangerous.
The original std::string was not trivially convertible to const char *, since the string object was not originally intended/required to store a null-terminator character. Under those circumstances, conversion to const char * was a potentially heavy operation that generally allocated an independent buffer and copied the entire controlled sequence to that buffer.
The independent buffer mentioned above (if used) had potentially "unexpected" lifetime. Any modifying operation on the original std::string object triggered invalidation/deallocation of that buffer, rendering previously returned pointers invalid.
It is never a good idea to implement such heavy and dangerous operations as implicitly-invokable conversion operators.
The original C++ standard (C++98) did not have such feature as explicit conversion operators. (They first appeared in C++11.) A dedicated named member function was the only way to somehow make the conversion explicit in C++98.
Today, in modern C++, we can define a conversion operator and still prevent it from being used implicitly (by using explicit keyword). One can argue that under such circumstances implementing the conversion by an operator is a reasonable approach. But I'd still argue that it is not a good idea. Even though the modern std::string is required to store its null-terminator (i.e. c_str() no longer produces an independent buffer), the pointer returned by the conversion to const char * is still "dangerous": many modification operations applied to std::string object may (and will) invalidate this pointer. To emphasize the fact that this is not a mere safe and innocent conversion, but rather an operation that produces a potentially dangerous pointer, it is quite reasonable to implement it by a named function.
So I have this little snippet where it thinks "abc" isn't a string but rather a const char [4], and so I can't assign it to my object. I've searched but haven't found any working solutions. Thanks in advance.
Tekst t = "abc";
Tekst Tekst::operator=(std::string& _text){
return Tekst(_text);
}
Edit: since this is a major staple of almost every exercise in my Object Oriented Programming class, due to whatever reasons, we can't change anything that's in int main(), so changing Tekst t = "abc"; is a no-go.
Edit 2:Tekst(std::string _text) :text(_text) {};
Compiler doesn't think "abc" is a const char [4]. It is const char [4] and you think that it should be std::string, which is not correct. std::string can be implicitly constructed from const char *, but they are nowhere near the same.
You problem is actually that you're trying to bind a temporary to a non-const reference, which is impossible in C++. You should change the definition of your operator to
Tekst Tekst::operator=(const std::string& _text){
// ^ const here
return Tekst(_text);
}
This will make your operator technically valid (as in, it compiles and there is no Undefined Behaviour). However, it does something very non intuitive. Consider the following:
Tekst t;
t = "abc";
In this example, t will not have any "abc" inside. The newly returned object is discarded and t is unchanged.
Most likely, your operator should look like this:
Tekst& Tekst::operator=(const std::string& _text){
this->text = _text; //or however you want to change your object
return *this;
}
Refer to the basic rules and idioms for operator overloading for more information about what is and what isn't expected in each operator.
On a semi-related note, you can have std::string from literal in C++14 and up:
#include <string>
using namespace std::string_literals;
int main() {
auto myString = "abc"s;
//myString is of type std::string, not const char [4]
}
However, this wouldn't help with your case, because the main problem was binding a temporary to non-const reference.
Thanks to #Ted Lyngmo, "This should help: godbolt.org/z/j_RTHu", turns out all i had to do was add a separate constructor for taking in const char*
Tekst(const char* cstr) : Tekst(std::string(cstr)) {}
Tekst t = "abc"; is just syntax sugar for Tekst t("abc"); which means it does not even consider your operator= at all, it uses the class's constructor instead.
In order for Tekst t = "abc"; to compile, you need a constructor that accepts either a const char* or a const std::string& as input. However, the constructor you showed takes a std::string by value instead of by const reference, so it can't be used for string literals. So you need to add a new constructor for that:
Tekst(const char *_text) :text(_text) {};
I was trying to understand the usage of explicit keyword in c++ and looked at this question on SO
What does the explicit keyword mean in C++?
However, examples listed there (actually both top two answers) are not very clear regarding the usage. For example,
// classes example
#include <iostream>
using namespace std;
class String {
public:
explicit String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
String::String(int n)
{
cout<<"Entered int section";
}
String::String(const char *p)
{
cout<<"Entered char section";
}
int main () {
String mystring('x');
return 0;
}
Now I have declared String constructor as explicit, but lets say if I dont list it as explicit, if I call the constructor as,
String mystring('x');
OR
String mystring = 'x';
In both cases, I will enter the int section. Until and unless I specify the type of value, it defaults to int. Even if i get more specific with arguments, like declare one as int, other as double, and not use explicit with constructor name and call it this way
String mystring(2.5);
Or this way
String mystring = 2.5;
It will always default to the constructor with double as argument. So, I am having hard time understanding the real usage of explicit. Can you provide me an example where not using explicit will be a real failure?
explicit is intended to prevent implicit conversions. Anytime you use something like String(foo);, that's an explicit conversion, so using explicit won't change whether it succeeds or fails.
Therefore, let's look at a scenario that does involve implicit conversion. Let's start with your String class:
class String {
public:
explicit String(int n); // allocate n bytes to the String object
String(const char *p); // initializes object with char *p
};
Then let's define a function that receives a parameter of type String (could also be String const &, but String will do for the moment):
int f(String);
Your constructors allow implicit conversion from char const *, but only explicit conversion from int. This means if I call:
f("this is a string");
...the compiler will generate the code to construct a String object from the string literal, and then call f with that String object.
If, however, you attempt to call:
f(2);
It will fail, because the String constructor that takes an int parameter has been marked explicit. That means if I want to convert an int to a String, I have to do it explicitly:
f(String(2));
If the String(char const *); constructor were also marked explicit, then you wouldn't be able to call f("this is a string") either--you'd have to use f(String("this is a string"));
Note, however, that explicit only controls implicit conversion from some type foo to the type you defined. It has no effect on implicit conversion from some other type to the type your explicit constructor takes. So, your explicit constructor that takes type int will still take a floating point parameter:
f(String(1.2))
...because that involves an implicit conversion from double to int followed by an explicit conversion from int to String. If you want to prohibit a conversion from double to String, you'd do it by (for example) providing an overloaded constructor that takes a double, but then throws:
String(double) { throw("Conversion from double not allowed"); }
Now the implicit conversion from double to int won't happen--the double will be passed directly to your ctor without conversion.
As to what using explicit accomplishes: the primary point of using explicit is to prevent code from compiling that would otherwise compile. When combined with overloading, implicit conversions can lead to some rather strange selections at times.
It's easier to demonstrate a problem with conversion operators rather than constructors (because you can do it with only one class). For example, let's consider a tiny string class fairly similar to a lot that were written before people understood as much about how problematic implicit conversions can be:
class Foo {
std::string data;
public:
Foo(char const *s) : data(s) { }
Foo operator+(Foo const &other) { return (data + other.data).c_str(); }
operator char const *() { return data.c_str(); }
};
(I've cheated by using std::string to store the data, but the same would be true if I did like they did and stored a char *, and used new to allocate the memory).
Now, this makes things like this work fine:
Foo a("a");
Foo b("b");
std::cout << a + b;
...and, (of course) the result is that it prints out ab. But what happens if the user makes a minor mistake and types - where they intended to type +?
That's where things get ugly--the code still compiles and "works" (for some definition of the word), but prints out nonsense. In a quick test on my machine, I got -24, but don't count on duplicating that particular result.
The problem here stems from allowing implicit conversion from String to char *. When we try to subtract the two String objects, the compiler tries to figure out what we meant. Since it can't subtract them directly, it looks at whether it can convert them to some type that supports subtraction--and sure enough, char const * supports subtraction, so it converts both our String objects to char const *, then subtracts the two pointers.
If we mark that conversion as explicit instead:
explicit operator char const *() { return data.c_str(); }
...the code that tries to subtract two String objects simply won't compile.
The same basic idea can/does apply to explicit constructors, but the code to demonstrate it gets longer because we generally need at least a couple of different classes involved.
I have below class in VS2010-SP1, Ternary operator and if-else seems to be working differently for below code on getname method
template <int size=120> class StringBuf{
public:
StringBuf(const char* src){
strcpy(s,src);
}
// Copy from another StringBuf
StringBuf(const StringBuf& src){
strcpy(s,src.get());
}
// String access
operator const char*() const {return get();}
const char* get() const { return s ; }
private:
char s[size];
};
class MyPony{
StringBuf<10> name;
public:
MyPony(char* name_) : name(name_){}
const char* getname(bool bVal){
//if( bVal )
// return name;
//else
// return "Jimmy";
return (bVal==true) ? name : "Jimmy";
}
};
int main(){
MyPony pony("Pani");
const char* getname = pony.getname(true);
return 0;
}
If I use ternary operator getname() method makes a copy of name by calling copy constructor and then calls operator const char* on the temp copy.
If I change ternary operator into if-else the code just calls operator const char* without making a temp copy.
My understanding is that if else and ternary operator should behave the same, but why is this different behavior for this class? Is there something that I'm overlooking?
For ternary operator VS2005 seems to call operator const char* directly .
Of course: The type of the conditional expression a ? b : c is the common type of b and c, which in your case is StringBuf<10>. So either operand must first get converted to that type before the resulting value can be considered for return.
There conditional expression is an expression, and the if statement is a statement. They're different things for different purposes. Use the if statement in your situation.
You might wonder why the common type is StringBuf<10> and not char const *. That's because of C++11 5.16/3 ("Conditional operator"), which says that implicit conversions are considered. In your case, there is an implicit conversion from char const [6] (the type of "Jimmy") to StringBuf<10>, but not the other way round, so the common type is uniquely defined. For comparison, if you tried x ? name : static_cast<char const *>("Jimmy"), that would not compile.