Thread: For Advanced C++ Programmers only #2. "returning address of local variable"

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    31

    Post For Advanced C++ Programmers only #2. "returning address of local variable"

    Code:
    inline void* GetArrayVariableFromType(void* data, size_t location, variabletype::e_type type)
    {
    
        switch (type)
        {
    
           case variabletype::_bool:
           {
              return &((std::vector<_bool>*)data)->operator[](location);
           }
           break;
      
       }
    
       return NULL;
    
    }
    Any idea why would this give me the following error:

    warning C4172: returning address of local variable or temporary

  2. #2
    Registered User
    Join Date
    Sep 2015
    Posts
    31
    Do I really have to use std::_Vb_reference?

  3. #3
    Registered User
    Join Date
    Sep 2015
    Posts
    31
    I just found out std::vector<int> returns int& for operator[]
    std::vector<bool> returns std::_Vb_reference.

    Weird...

  4. #4
    Registered User
    Join Date
    Sep 2015
    Posts
    31
    Found out std::vector<bool> packs data into 1 bit, preventing me from pointing a boolean to its data. The workaround is to use std::vector<char> instead of std::vector<bool>.

    Fixed.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Code:
    template<typename T>
    inline T GetArrayVariableFromType(vector<T> &data, size_t location, variabletype::e_type type)
    {
       switch(type) 
       {
       case variabletype::_bool:
           return data[location];
       default:
           throw runtime_error(__func__ /* C++11 */ ); 
       }
       return T(); // appease the compiler
    }
    I suppose it's debatable, but this seems more robust anyway. No reason to stop using vector<bool> because of bit-packing.
    Last edited by whiteflags; 07-23-2016 at 10:21 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble with unassigned local variable "path"
    By Quentin Botha in forum C# Programming
    Replies: 14
    Last Post: 10-10-2014, 01:37 PM
  2. Marking functions as "Local" or "Global"
    By zyxwvuts in forum C Programming
    Replies: 10
    Last Post: 02-22-2014, 07:58 AM
  3. Returning the Address of a Local Variable (Array)
    By Jesdisciple in forum C Programming
    Replies: 9
    Last Post: 08-20-2008, 02:03 AM
  4. Should "static" variable always be local to a file?
    By meili100 in forum C++ Programming
    Replies: 3
    Last Post: 06-22-2008, 11:51 PM
  5. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM

Tags for this Thread