J
Johannes Bauer
Hello Group,
please consider the following code
#include <vector>
#include <iostream>
#define USE_CONST
#define USE_STRING
class a {
public:
#ifdef USE_CONST
const std::string &moo;
a(const std::string &moo) : moo(moo) { };
#else
std::string &moo;
a(std::string &moo) : moo(moo) { };
#endif
void show() {
std::cerr << "String: '" << moo << "'" << std::endl;
};
};
int main() {
#ifdef USE_STRING
std::string str = std::string("Das ist ein Test!");
a abc = a(str);
abc.show();
#else
a xyz = a(std::string("Das ist ein Test!"));
xyz.show();
#endif
return 0;
}
There are four possible combinations of USE_CONST and USE_STRING:
1 USE_STRING && !USE_CONST => Fine
2 USE_STRING && USE_CONST => Fine
3 !USE_STRING && !USE_CONST => Compile Error
4 !USE_STRING && USE_CONST => Compiles, but behaves weird
So it is clear to me that when using number 3, the compiler throws an
error - since the created string object goes out of scope (and lifespan)
immediately after the constructor of "a" is called.
But what bewilders me a bit is that example #4 compiles cleanly without
any warning - yet there is no string output (it's just empty); probably
because it has already been destroyed when the implicit std::string's
destructor was called.
This seems intriguing. The string is already destroyed, however a may
keep a reference (moo) to it? How is that possible?
Greetings,
Johannes
please consider the following code
#include <vector>
#include <iostream>
#define USE_CONST
#define USE_STRING
class a {
public:
#ifdef USE_CONST
const std::string &moo;
a(const std::string &moo) : moo(moo) { };
#else
std::string &moo;
a(std::string &moo) : moo(moo) { };
#endif
void show() {
std::cerr << "String: '" << moo << "'" << std::endl;
};
};
int main() {
#ifdef USE_STRING
std::string str = std::string("Das ist ein Test!");
a abc = a(str);
abc.show();
#else
a xyz = a(std::string("Das ist ein Test!"));
xyz.show();
#endif
return 0;
}
There are four possible combinations of USE_CONST and USE_STRING:
1 USE_STRING && !USE_CONST => Fine
2 USE_STRING && USE_CONST => Fine
3 !USE_STRING && !USE_CONST => Compile Error
4 !USE_STRING && USE_CONST => Compiles, but behaves weird
So it is clear to me that when using number 3, the compiler throws an
error - since the created string object goes out of scope (and lifespan)
immediately after the constructor of "a" is called.
But what bewilders me a bit is that example #4 compiles cleanly without
any warning - yet there is no string output (it's just empty); probably
because it has already been destroyed when the implicit std::string's
destructor was called.
This seems intriguing. The string is already destroyed, however a may
keep a reference (moo) to it? How is that possible?
Greetings,
Johannes