lunduniversity.lu.se

Computer Science

Faculty of Engineering, LTH

Denna sida på svenska This page in English

Loose ends

Here we sort out any unresolved questions from the lectures and labs.

 

1. Returning a reference from a function

Lecture slide 85 contained the following function:

int& element(const int* x, size_t i) {
   // ... could insert index check here
   return x[i];

Is it really OK to return X[i], which is a const int, when the function return type is int& (not const)?

Answer: No, the slide contained an error. The function should look like this:

int& element(int* x, size_t i) {
   // ... could insert index check here
   return x[i];
}

Alternatively (allthough const_cast should be avoided if possible):

int& element(const int* x, size_t i) {
   // ... could insert index check here
   return const_cast<int&>(x[i]);
}

The lecture slide has been updated.

Loose ends 2016

1. Are there support for multi-byte strings in C++?

Yes. In addition to the normal string class there are a number of variants of the class for multi-byte strings:

  • std::wstring
  • std::u16string (from C++11)
  • std::u32string (from C++11)

All of the string classes above (including string) are actually instances of the template class std::basic_string:

  • std::string = std::basic_string<char>
  • std::wstring = std::basic_string<wchar_t>
  • std::u16string = std::basic_string<char16_t>
  • std::u32string = std::basic_string<char32_t>


2. Explicit constructors - Slide 105

In lecture slide 105, an explicit declaration can be used to prevent the constructor String(size_t s) from being implicitly used in the call f('a') to convert the 'a' to a String to create the proper parameter to f.

Question: Does explicit also means that the parameter to the String(size_t) constructor must be exactly of type size_t, or can it be of an arbitrary integer-compatible type?

Answer: It can be of any size_t-compatible type (including char!!!). Declaring the constructor explicit does not prevent us from creating a String from a char (like 'a'). This can still be done by writing "String('a')". It only means that the compiler will not do so implicitly. To call the function f with a character as the length of the string (why would you like to do that?) you would have to write "f(String('a'))". Note especially that the following code is not allowed: "size_t i=1; f(i);", but "f(String(i))" is.

3. Overloading the postfix version of operator++ (x++)

Question: When overloading the postfix operator ++ (x++) a dummy int parameter is used to mark that it is the postfix version of ++ that is being overloaded. Should it always be an int?

Answer: Yes, it should always be an int.