Domanda

I was reading an article about effectively using auto_ptr. In there, the following code was suggested as a correct piece of code:

// Example 10(c): Correct (finally!)
//
auto_ptr<String> f()
{
  auto_ptr<String> result = new String;
  *result = "some value";
  cout << "some output";
  return result;  // rely on transfer of ownership;
                  // this can't throw
}

But as far as I am aware, the assignment operator of auto_ptr only accepts another auto_ptr as the rhs -- to avoid accidental misuse. So, is the following line a typo in the article, or is it really suppposed to work?

auto_ptr<String> result = new String;
È stato utile?

Soluzione

That line is indeed incorrect, but not for the reasons you think. It doesn't call the assignment operator, but instead calls the constructor. When you say = when you first declare an object, it doesn't create the object and then call the assignment operator. Rather, it just calls the constructor and passes that as an argument. So from this stand point, it's "correct" because it's using the constructor, not the assignment operator

Or at least it would if it could. You'll notice std::auto_ptr's constructor takes a pointer. However, it's marked explicit, which means that the above "shortcut" isn't allowed. You have to explicitly call the constructor (with parentheses), and cannot use = as a shortcut to do so. This is why it's incorrect. If, instead, they said auto_ptr<String> result(new String);, all would be fine. Also, if the constructor wasn't marked explicit, all would be fine. But as it is, it is not correct.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top