Take the 2-minute tour ×

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;
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
You are right, +1. –  jogojapan Nov 28 '12 at 6:10
But regarding your comment to healer's (now deleted) answer: Of course this involves the copy constructor. Your answer is right about the reason why the initialization as stated in the question does not work. But it is also correct that this is copy initialization, which involves the copy constructor. (The actual call to the copy constructor may be optimized away, but that is a different matter.) –  jogojapan Nov 28 '12 at 6:32
@jogojapan: Hmmm, learn something new every day. Is there somewhere I can read more (in less legalese than the standard) about exactly when constructors are called that will explain that more (before the compiler optimizes them away)? –  Cornstalks Nov 28 '12 at 6:39
I don't know really... there are some good SO posts, e.g. this one stackoverflow.com/questions/1051379/…. The one I learned from the most is this: stackoverflow.com/questions/12372442/…, although that one is terrible to read and only understandable when you read the Standard in parallel. –  jogojapan Nov 28 '12 at 7:13

Your Answer


