Avoid copying when invoking delegate constructors

Class with delegating constructors

class A {
  A(SomeObject obj,   // requires a new copy of the object 
    int x,
    const string& y
  ) { // additional logic }
  A(SomeObject obj, const string& y)   
    :A(obj, 0, y) {}     // will obj be copied?
};

Intended use:

SomeObject obj;
A a1(obj, "first");
A a2(obj, "second");

The construction is to build SomeObjectexactly once when the construction is performed A. Will it pass objto create a copy SomeObjectwhen delegating to another constructor? If so, how can I avoid this?

+4
source share
2 answers

Yes, it is objcopied when delegating to another constructor: this is not a valid context for copy elision or even for automatic movement .

std::move ( ) const. (public) - , ++ 11.

+7

. . , , , , , . . :

mem-initializer , - , . mem-initializer-id , mem-; , , mem-, . . . , , .

, Copied :

#include <iostream>

struct Foo {
    Foo() = default;
    Foo(const Foo&) {
        std::cout << "Copied";
    }
};

struct A {
    A(Foo f, int i) { }
    A(Foo f) : A(f, 0) { }
};

int main() {
    A a{Foo{}};
}
-6

Source: https://habr.com/ru/post/1691655/


All Articles