0

It is possible to push_back vector elements in one line when it contains pointers:

vector<SomeClass*> v;
v.push_back(new SomeClass(initVar1));
v.push_back(new SomeClass(initVar2));
v.push_back(new SomeClass(initVar3));

Is there a way to do one-line push_backs like this with non-pointer variables (which are necessarily copies of other variables)?

Chris Redford
  • 16,982
  • 21
  • 89
  • 109

1 Answers1

6

If they have public copy constructors, of course:

v.push_back(SomeClass(initVar));

Note that push_back creates a copy anyway, so it seems pointless to me. In C++11 the object will be move constructed if possible.

Also, save yourself a headache and use std::unique_ptr<T> instead of raw pointers for your vector elements. Using raw pointers in that way completely disables the vector's ability to manage memory for you, defeating half the purpose of using it to begin with.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • Awesome, thanks. You may want to edit your example to say `initVar1` because `some_instance` made me think you were talking about a copy constructor on a current instance. Which would require me to instantiate that instance and defeat the entire purpose of trying to do it in one line. – Chris Redford Feb 28 '13 at 00:47
  • Does unique_ptr work with polymorphism? E.g. `unique_ptr b = new Derived()`? – Chris Redford Mar 07 '13 at 19:28
  • 1
    @ChrisRedford: Yes, it follows the rules of C++. You can pass in a pointer to a child class like you would be able to in any other situation; `std::unique_ptr b(new Derived());` – Ed S. Mar 07 '13 at 21:12