Sao không thử universal reference?, 1 ctor là đủ.C++:Foo(std::string&& s, int n) : name{std::move(s)} // move ctor , value{n} { }
nhưng xài rvalue ref vẫn vướng 1 cách truyềnđó là truyền const lvalue vào:![]()
thế là phải viết thêm 1 ctorC++:const std::string default{"default"}; foos.emplace_back(default, 0); // rvalue ref ko bind vào const lvalue được, báo lỗiFoo(const std::string&, int)à? Cái này đụng chạm quy luật DRY dont repeat yourselfC++ rác vậy xao![]()
![]()
nhưng ko, truyền copy to the rescue![]()
![]()
![]()
C++:Foo(std::string s, int n) : name{std::move(s)} // move ctor , value{n} { }![]()
https://godbolt.org/z/qonTMzrGv
C++:
#include <cstdio>
#include <utility>
struct A {
A() = default;
A(A const &a) { std::puts("copy"); }
A(A&& a) { std::puts("move"); }
};
struct Foo {
template <typename T>
Foo(T &&t, int n) : a{std::forward<T>(t)}, value{n}
{
}
A a;
int value;
};
int main()
{
A a;
const A a2;
std::fputs("Foo f1{a, 1}: ", stdout);
Foo f1{a, 1};
std::fputs("Foo f2{std::move(a), 1}: ", stdout);
Foo f2{std::move(a), 1};
std::fputs("Foo f3{A{}, 1}: ", stdout);
Foo f3(A{}, 1);
std::fputs("Foo f4{a2, 1}: ", stdout);
Foo f4{a2, 1};
std::fputs("Foo f5{std::move(a2), 1}: ", stdout);
Foo f5{std::move(a2), 1};
std::fputs("Foo f6{A{a2}, 1}: ", stdout);
Foo f6{A{a2}, 1};
}
Foo f1{a, 1}: copy
Foo f2{std::move(a), 1}: move
Foo f3{A{}, 1}: move
Foo f4{a2, 1}: copy
Foo f5{std::move(a2), 1}: copy
Foo f6{A{a2}, 1}: copy
move



công ty cũ cũ dùng c++03, đến tận 2020 chuyển sang công ty cũ mới được dùng c++11. Nghĩ nó đau lòng
Chắc em phải học theo bác dù đang thất nghiệp