PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] What is the most efficient (or just best practice) way to set up a function that returns a reference to an std:vector but sometimes a default empty?

 July 10, 2022     c++, reference, return     No comments   

Issue

Take the following function (which obviously doesn't compile).

const std::vector<int>& getMyVector()
{
    if (something)
        return std::vector<int>();

    if (somethingElse)
        return m_myVector;

    return std::vector<int>();
}

Assume that m_myVector is large or is otherwise not well suited to being returned by copy and so must be returned by reference.

What is the most efficient way to structure the code to allow this logic while also allowing a return by reference? I can see two options. The first would be to change this to return a pointer to the vector instead of a reference and then return null instead of an empty vector. The other would be to have a static const empty vector and return that. I don't particularly like either of those options, so I'm wondering if there's a better way.

Edit: Please don't use the example function as a literal representation of what I'm trying to illustrate. The point is that I have a function that can either return a real vector full of data or it can return a default empty vector based on certain conditions. Also, if it matters, my real code isn't even returning a simple member variable, it's a vector that's stored inside a hash_map.


Solution

Despite your hesitations, I recommend defining a static empty result vector wherever you have defined m_myVector.

std::vector<int>              m_myVector;
static const std::vector<int> m_emptyResult;

Your code can then both compile and avoid copies.

const std::vector<int>& getMyVector()
{
    if (something)
        return m_emptyResult;

    if (somethingElse)
        return m_myVector;

    return m_emptyResult;
}

Or more tersely:

const std::vector<int>& getMyVector()
{
    if ( !something && somethingElse )
        return m_myVector;

    return m_emptyResult;
}


Answered By - Drew Dormann
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing