Home > front end >  If we convert a value with one constructor, will there also be copy constructor needed to copy the n
If we convert a value with one constructor, will there also be copy constructor needed to copy the n

Time:02-01

I am having a trouble understanding the topic, and so it might be a stupid question but I am still wondering:

When we have a function, for example:

void func(const StringClass & param1, const StringClass & param2);

And then we pass to the function for example, a C string:

func("test", test);

Where "test" is a C string and test is an object of our StringClass. And let's say our StringClass has defined a copy constructor and also a conversion constructor which can convert our "test" C string into a StringClass object. I have tested it already and what I have seen is that, that there is only conversion happening and not copying, and for the other object there is only assignment which I understand, since we pass it by reference. If our function is declared like this:

void func(const StringClass param1, const StringClass param2);

And we still pass previous arguments func("test", test), then the first argument gets converted, but no copy constructor is invoked. And for the second parameter copy constructor is invoked.

But my question is - will it always be like that? I mean, can other compiler treat it like that: convert the "test" C string into a StringClass object and then use the copy constructor to copy the temp object to param argument inside the function, or a conversion is enough since it creates a temp object anyways, so it won't differ between compilers?

CodePudding user response:

As a first hint you can add a copy constructor that prints something to see if it gets called:

#include <iostream>

struct foo {
    template <size_t n>
    foo(const char(&str)[n]){
        std::cout << "converting constructor\n";
    }
    foo(const foo& f){
        std::cout << "copy constructor\n";
    }
};

void bar(foo){}

int main() {
    bar("asdf");
}

Output is:

converting constructor

No copy constructor is called in this example. This is only a hint, because it is the output with one specific compiler and one specific C standard. However, once a foo has been created by calling the converting constructor, there is no reason to call the copy constructor. The string literal "asdf" is converted to a foo and thats it. There is no additional copy in the code, hence no compiler should create another copy.

  •  Tags:  
  • Related