Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
#include <string>
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<std::string> StringPtr;
StringPtr f() {
return StringPtr(new std::string);
}
int main() {
StringPtr ptr1(new std::string);
StringPtr ptr2 = ptr1;
StringPtr ptr3 = f();
}
struct Test
{
Test() : s("s") {}
Test(const Test& other) : s(other.s) { puts("Test(const Test& other)"); }
std::string s;
};
int main()
{
Test t1{};
Test t2(std::move(t1));
puts(t1.s.c_str());
puts(t2.s.c_str());
return 0;
}
Test(const Test& other)
s
s
The copy constructor is called whenever an object is initialized from another object of the same type, which includes
initialization, T a = b; or T a(b);, where b is of type T
function argument passing: f(a);, where a is of type T and f is void f(T t)
function return: return a; inside a function such as T f(), where a is of type T, which has no move constructor.
struct Test
{
Test() : s("s") {}
Test(const Test& other) : s(other.s) { puts("Test(const Test& other)"); }
Test(Test&& other) = default;
std::string s;
};
//...
s
struct Test
{
Test() : s("s") {}
Test(const Test& other) : s(other.s) { puts("Test(const Test& other)"); }
Test(Test&& other) = delete;
std::string s;
};
Test t2(std::move(t1));
delete, то copy-constructor НЕ вызывается#include <iostream>
using namespace std;
struct Foo
{
void foo(char a)
{
cout << (int)a << endl;
}
};
struct Bar
{
void bar(char a)
{
cout << (int)a << endl;
}
void bar(int a); // да-да, оно только объхявлено
};
int main()
{
char a = 100;
int b = 50;
Foo foo;
Bar bar;
foo.foo(a); // ок, печатает 100
foo.foo(b); // ок, печатает 50
bar.bar(a); // ok, печатает 100
bar.bar(b); // ошибка копиляции
return 0;
}
...the candidate functions are selected as follows:
...When initializing a temporary to be bound to the first parameter
of a constructor that takes a reference to possibly cv-qualified T as its first argument, called with a
single argument in the context of direct-initialization of an object of type “cv2 T”, explicit conversion
functions are also considered…
A defaulted move constructor or assignment operator (12.8) that is defined as deleted is excluded from the
set of candidate functions in all contexts.
Пополняем шпаргалки по C++: неявно-генерируемые перемещающий конструктор и оператор присваивания