Why is it OK to return a 'vector' from a function?

i return everything i buy
anxiety about returning items
acceptable reasons for returns
how to return a vector in c++
returning a std vector
c++ return vector by reference
how to return a vector from a function cpp
how to return a vector type function

Please consider this code. I have seen this type of code several times. words is a local vector. How is it possible to return it from a function?

Can we guarantee it will not die?

 std::vector<std::string> read_file(const std::string& path)
    std::ifstream file("E:\\names.txt");

    if (!file.is_open())
        std::cerr << "Unable to open file" << "\n";

    std::vector<string> words;//this vector will be returned
    std::string token;

    while (std::getline(file, token, ','))

    return words;

Can we guarantee it will not die?

As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

The local variable will go out of scope. after it was moved (or copied).

Top 10 Reasons for a Product Return, they broke. They may no longer use or need the product. Or an upgraded product is available, and they want to own that product instead. It can also happen because a customer was forced to move, change jobs or just downsize their personal life. You can check the status of your Oklahoma income tax refund for the current year by one of the following ways: Visiting our online Taxpayer Access Point You will be required to give the last seven digits of the primary (first) social security number or individual taxpayer identification number (ITIN) on the return, the amount of the anticipated refund and the ZIP code on the return.

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.


The function will move the value. See this answer for further details.

Is it common for people to buy clothes, wear them once, and return , the item. Some stores allow returns but only for a certain amount of time. A salute is a sign of respect (at least of a rank, if not of the individual in question), and the return of a salute is the second half of the mutual respect equation. One of the most disrespectful things an officer in the military can do is fail to return a salute given by someone more junior to them.

I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.

But in this case, it works, because the std::vector is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]

As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.

What Happens to Customer Returns?, The longer a store allows you to return something after purchasing, the that bad,'” Ryan Freling, one of the co-authors of the meta-analysis,  I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.

To well understand the behaviour, you can run this code:

#include <iostream>

class MyClass
    MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
    ~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
    MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
    MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }

MyClass my_function()
  std::cout << "run my_function()" << std::endl;
  MyClass a;
  std::cout << "my_function is going to return a..." << std::endl;
  return a;

int main(int argc, char** argv)
  MyClass b = my_function();

  MyClass c;
  c = my_function();

  return 0;

The output is the following:

run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()

How to Return Something You've Bought in a Shop: 12 Steps, We have first do understand how the two languages represent data: [code]a=b; a.x=2; b.x=3; [/code]What is the value of [code ]a.x[/code] now? * in JAVA will be  Returning home can be both physically and mentally challenging. Above all, use caution. You may be anxious to see your property but do not return to your home before the area is declared to be safe by local officials.

I do not agree and do not recommend to return a vector:

vector <double> vectorial(vector <double> a, vector <double> b)
    vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
    return c;

This is much faster:

void vectorial(vector <double> a, vector <double> b, vector <double> &c)
    c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];

I tested on Visual Studio 2017 with the following results in release mode:

8.01 MOPs by reference 5.09 MOPs returning vector

In debug mode, things are much worse:

0.053 MOPS by reference 0.034 MOPs by return vector

The Weird Psychology of Returning Stuff to the Store, It is ok for a method to return a reference of a subtype of the type declared as its return type. This is called ”covariant return types.” For example, if a method  Electronically submitting your tax return to the IRS is more secure than paper filing because the return is transmitted directly to the IRS computer system. Your refund is likely to be processed faster because e-filing means the IRS doesn't have to sort or re-transcribe your tax return at their service center.

Why is it OK to return an array in Java but not in C?, This is bad news for companies any time of year, because even if the buyer pays the return shipping costs, there usually are additional  But once you're feeling a bit better, it's surprisingly hard to know when you're not contagious anymore and, therefore, when it's OK to go back to work and be around other people without risking

OCAJP Associate Java 8 Programmer Certification Fundamentals: 1Z0-808, 1 auto f () { } // OK, return type is void 2 auto* g() { } // error, cannot deduce auto* from void () If the type of an entity with an undeduced placeholder type is needed​  Why Did My Period Return A Year After Stopping? After not having a period for one year, it returned this morning. I have previously had many of the symptoms of menopause, including hot flashes and

The Psychological Reason Why People Habitually Return Items , Top Reasons For Product Returns. Let me first say this: a product return isn't necessarily a bad thing. I say that with confidence…and it's based  The System Restore tool can be accessed a number of ways in Windows. Once started, this utility is designed as a step-by-step wizard, making it really easy to choose a point in the past, called a restore point, to return your important files and settings to.

  • It get copied when return.
  • No one guarantees.. It will die, but after it's copied.
  • You only have a problem if your function returns a reference : std::vector<std::string>&
  • @songyuanyao no, it will be moved.
  • @songyuanyao Yes. C++11 is the current standard, so C++11 is C++.
  • But is the efficient or have any performance concerns say for vector which may hold 1000 entries?
  • @zadane Was this in question? Also I mentioned moving that will avoid to take a copy of the return value actually (available at least with the current standard).
  • No not really in the question but I was looking for answer from that perspective independently. I don't know if I post my question, I am afraid they will mark it duplicate of this :)
  • @zadane "I am afraid they will mark it duplicate of this" Could well be. Just have a look at the higher voted answer. Even for older implementations you shouldn't worry, those will be mostly optimized correctly by those compilers anyway.
  • It will be moved, not copied. This is guaranteed.
  • Does this apply for C++10 as well?
  • There is no such thing as C++10.
  • C++03 had no move semantics (but copy may have been elided, though), but C++ is C++11 and the question was about C++.
  • There is a separate tag for questions exclusive to C++11. Many of us, especially programmers in larger companies are still stuck to compilers which don't fully support C++11 yet. I updated the question to be accurate for both standards.
  • ..........what. It seems clear that you're not qualified to throw around accusations like "failure of design". And in fact, the promotion of value semantics by RVO and move operations is one of the main successes of modern C++ style. But you seem to be stuck thinking about raw arrays and pointers, so I wouldn't expect you to grasp that.