Reputation: 2291
I have met a strange case: I have an object that have some string members, that I use to initialize some other members like here:
class A
{
private:
B b;
C c1;
C c2;
public:
A(const string& str) : b(str), c1(b.foo1()), c2(b.foo2()) {}
// ...
};
class B
{
public:
B(const string& str)
{
// ...
}
string& foo1()
{
string s1;
// initialization
return s1;
}
string& foo2()
{
string s2;
// initialization
return s2;
}
};
class C
{
private:
string s;
public:
C(const string& str) : s(str) {}
};
When I call the constructor of A:
string str = "some string here";
A(str);
I get the following error:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::replace
the problem is here:
A(const string& str) // str == "some string here"
: b(str), // enters the B(str), str == "some string here"
c1(b.foo1()), // enters the C(str), str the string that I want
c2(b.foo2()) // enters the C(str), but str is not visible
A::b
out of scope?foo1()
or foo2()
for initializing c2, the problem is the sameHow would you suggest me to do it?
Upvotes: 0
Views: 64
Reputation: 30597
You are returning references to local variables in both foo1 and foo2. These variable are limited in scope to the body of the functions in which they are defined. They disappear as soon as the function returns, so attempts to reference them after this cause your program to crash.
Upvotes: 2
Reputation: 71019
You are returning a reference to a local variable in foo1
and foo2
(s1
and s2
respectively) this is not allowed and using the reference will invoke undefined behavior.
Upvotes: 4