Using return value to pass into constructor doesn't work

150 views Asked by At

I'm using boost::property_tree::ptree and parse_ini to read an ini file. Using ptree::iterator I'm getting the ini sections and want to use them to create another object.

I have an object called First that gets First(int& i, string& str)

So I'm trying to build new object like that using the return values I get from the ptree functions for example (posision is my ptree::iterator)

First* one = new First(
    boost::lexical_cast<int>((posision->second).get<int>("number")),
    (posision->second).get<string>("name")
);

but I get

no matching function for call to ‘First::First(int, std::basic_string<char>)’

so I tried casting like this:

First* one = new First(
    (int&) boost::lexical_cast<int>((posision->second).get<int>("number")),
    (string&) (posision->second).get<string>("name")
);

but then I got

invalid cast of an rvalue expression of type ‘int’ to type ‘int&’

and

invalid cast of an rvalue expression of type ‘std::basic_string<char>’ to type ‘std::string&

will appreciate any help or explanation.

thanks !

1

There are 1 answers

2
sdzivanovich On BEST ANSWER

The issue is that you cannot pass r-values where the argument is typed as an l-value reference. E.g.

void foo(int& x)
{
    x = 2;
}

int main(void)
{
    foo(5); // won't compile; can't pass r-value to reference parameter
}

If this were valid, we would be assigning the value 2 to the value 5, which is nonsense. If it's possible, you can declare the First constructor to take const references (not sure if this works for you since you didn't post the code):

First(const int& i, const string& str);

Although for primitives, it's best to just pass as value instead of const reference:

First(int i, const string& str)

If you need them to be non-const references (which smells like a bad design), you can do:

int i = boost::lexical_cast<int>((posision->second).get<int>("number"));
string str((posision->second).get<string>("name"));
First* one = new First(i, str);