0

I thought that when doing this:

String s1 = "hello";

there are 2 operations happening (e.g., as said here): (1) constructing a temporary object with the string literal "hello", and then (2) copy-constructing s1 with the temporary object.

However, when running the following code, the only printing I get is from String's constructor, and not from its copy constructor. Why?

static char *AllocAndCpy(const char *src_);

class String
{
public:
    String(const char *string_="");
    String(const String &other_);
private:
    char *m_str;
};

String::String(const char *string_): m_str(AllocAndCpy(string_))
{
    std::cout << "constructor" << std::endl;
}

String::String(const String &other_):m_str(other_.m_str)
{
    std::cout << "copy constructor" << std::endl;
}

static char *AllocAndCpy(const char *src_)
{
    size_t src_length = strlen(src_)+1;
    char *dest_ = new char[src_length]; 
    return (static_cast<char *>(memcpy(dest_, src_, src_length))); 
}

int main()
{
    String s1 = "hello";
    return 0;
}
Community
  • 1
  • 1
OfirD
  • 9,442
  • 5
  • 47
  • 90
  • Are you compiling with or without optimization? or debug/release mode? – Alex Zywicki May 26 '16 at 15:27
  • compiled with no optimizations: i tried `-O` and also `-O0` to `-O3` – OfirD May 26 '16 at 15:32
  • and with `-DDEBUG` – OfirD May 26 '16 at 15:38
  • 1
    There's a flag like `-fno-elide-constructors` or something to disable this behaviour. Lowering optimization flags doesn't normally do it. – chris May 26 '16 at 15:40
  • 1
    I don't think most compilers change their behavior with regards to copy elision based on optimization levels. You have to specifically request they not do it (`-fno-elide-constructors` if using gcc or clang, for example) – Benjamin Lindley May 26 '16 at 15:40

0 Answers0