Re: temporary and unnamed objects
On Jan 20, 12:50 pm, "Austin" <austin_ci...@yahoo.com> wrote:
class String {
public:
String(const char* = "");
...
};
void print_heading(String)
...
print_heading("Annual Report");
I know that this call will invoke an implicit conversion, as the compiler
will write:
String temp("Annual Report");
print_heading(temp) //-> the temp object will be destoryed here
How about if I call the function using a unnamed object:
print_heading(String("Annual Report"))
My question is when the unnmaed object will be destroy? It will be
destroyed after the function all or the end of a local scope?
At end of local scope (print_heading(...)'s scope). However, we don't
know _how_ you are storing the literal string or any pointer/reference
to it. This is relevant here since you are passing that String by
value (don't do that). Any time you are passing parameters that are
not primitives, prefer a reference_to_constant.
void print_heading(const String& s) { }
As a suggestion, if you prefer not using std::string, how does a
std::vector< char > sound like?
Observe the lifetime of the temporary below, the fact that it exists
throughout the function's scope is guarenteed by the standard (binding
a reference_to_constant).
This toy String stores the terminator, which may _not_ be what you
want.
#include <iostream>
#include <ostream>
#include <iterator>
#include <vector>
template< typename T = char >
class String
{
std::vector< T > vt;
public:
// def ctor
String() : vt() { }
// parametized array ctor
template< const std::size_t Size >
String(const T(& array)[Size])
: vt(&array[0], &array[Size])
{
std::cout << "String(array)\n";
}
~String() { std::cout << "~String()\n"; }
// member functions
std::size_t size() const { return vt.size(); }
// friend op<<
friend
std::ostream& operator<<(std::ostream& os, const String< T >& s)
{
std::copy( s.vt.begin(),
s.vt.end(),
std::ostream_iterator< T >(os) );
return os;
}
};
void foo(const String<char>& s)
{
std::cout << "foo(const String&)\n";
}
int main()
{
{ // anonymous scope
String<> s("a short string");
std::cout << s << std::endl;
foo(s);
}
std::cout << "about to generate temporary...\n";
foo(String<>("a local string"));
std::cout << "back in main...\n";
}
/*
String(array)
a short string
foo(const String&)
~String() // end of anon scope
about to generate temporary...
String(array) // temp
foo(const String&) // foo body
~String() // end of local scope
back in main...
*/