A
A
aminought2016-09-11 19:22:52
C++ / C#
aminought, 2016-09-11 19:22:52

What C++ language operations can be potentially unsafe?

  • Assignment.
  • Using dynamic_cast to cast reference types.
  • Creating an instance of a class.
  • Implicit conversion of base type values.
  • Passing a class object to a function by value.

A multiple-choice question from a C++ course by Mail.ru. I don’t see the point in guessing, so I post the question here along with my thoughts. In general, I would first decide what it means - an unsafe operation? As far as I understand, this is an operation that will compile, but may somehow work incorrectly.
Assignment is a safe operation, checked at compile time.
Using dynamic_cast for reference types - an exception is thrown, which means unsafe.
Creating an instance of a class - may leak resources if an exception occurs in the constructor, and memory may run out - unsafe.
Implicit conversion is by definition unsafe, type checking is required.
Passing by value - may not have enough memory for a copy of the object, unsafe.
The answer is incorrect. I told my thoughts, now I ask for your help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nirvimel, 2016-09-11
@aminought

An assignment can be overloaded, so in general it can call arbitrary code that may not be safe, and therefore the operation itself cannot be considered safe.
As for the conversion of values ​​of basic types, everything is not so simple, it can lead to errors in program logic (if some edge case was not provided), but by itself (as a single action) cannot cause exceptions and undefined behavior if the operands are themselves valid (do not throw access exceptions).
The rest of the reasoning given is generally correct, I did not notice any obvious errors.

M
Maxim Moseychuk, 2016-09-11
@fshp

Using dynamic_cast for reference types - an exception is thrown, which means unsafe.

Safe operation, as the exception can be handled.

K
Konstantin Stepanov, 2016-09-11
@koronabora

Controversial: Assignment.
Yes: Using dynamic_cast to cast reference types.
Yes: Create an instance of the class.
Possible: Passing a class object to a function by value
With dynamic_cast, it is quite possible to run into a null pointer or the impossibility of casting.
When creating an instance, the constructor may fall or there may be no memory.
When assigning, in ordinary life, there should be no problems, but, in principle, they can be created by a banal redefinition of the assignment operator.
When passing by value, the copy constructor may be disabled, but this is determined at compile time, and, of course, there may not be enough memory on the stack.
Z.Y. As far as I understand, the implicit conversion of base types is checked at compile time, unless, of course, we use auto.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question