简体   繁体   中英

std::initializer_list to return member variables returns incorrect values

Is there any issue with returning the multiple values from function using std::initializer_list . In following code when I try to print the values returned using std::initializer_list , I am getting junk values.

header file

#ifndef _C17_CONSTRUCT_3_HPP
#define _C17_CONSTRUCT_3_HPP

#include <iostream>
#include <string>
#include <initializer_list>

class A {
    public:
        A(int a,int b):a{a},b{b}{}
        std::initializer_list<int> return_init_list()
        {
            std::initializer_list<int> local_list = {a, b};
            std::cout<<"a "<<a<<" b "<<b<<std::endl;
            return local_list;
        }
    private:
        int a{9};
        int b{10};
};
#endif

Source file

#include "c17_construct_3.hpp"

int main()
{
    A a{9, 10};
    std::initializer_list<int> ret = a.return_init_list();
    std::cout<<"ret list size "<<ret.size()<<std::endl;

    for(auto list_elem : ret)
        std::cout<<list_elem<<std::endl;
}

Output

a 9 b 10  
ret list size 2  
-1489302992  
32692  

std::initializer_list is not a container, you cannot use it to return a list of items from a function. When you write the following

std::initializer_list<int> local_list = {a, b};

the compiler translates that into code functionally similar to the following

const int __temp_array[2] = {a, b};
std::initializer_list<int> local_list{__temp_array, __temp_array + 2};  
// the above line assumes the implementation has access to such a constructor

An almost identical example can be found in the standard - §8.5.4/5 [dcl.init.list]

In your code the temporary array containing copies of a and b ceases to exist when the function return_init_list() returns. Use std::pair or std::tuple to return the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM